我正在尝试创建一个高级的、可重用的查询函数。
我需要按类别或类别+标记进行查询。
我知道如何处理自定义字段(元查询),但如何处理简单的类别和标记?
伪SQL查询将是:
Select * from Posts where ( cat_id = 1 OR (cat_id = 5 AND tag_id = 6) )
查询可能会更改为需要包含一组标记
Select * from Posts where ( cat_id = 1 OR ( cat_id = 5 AND tag_id = (5,6,7) ))
目前我正在使用wp\\u query并传递参数,但我想如果需要的话,我可以编写一个一次性的query\\u帖子。
这是我自定义查询的粗略版本。我想我需要为我想要的“or”语句添加另一个参数?
$args = array(
\'post_type\' => $postType, //assume \'post\'
\'cat\' => $cat_id, //currently a single id
\'orderby\' => \'date\',
\'post_status\' => \'publish\',
);
我得到了一些帮助
Best practice for multiple queries on page所以现在我需要添加一个tax\\u查询,但这里是查询失败的地方
$taxQuery = array(
\'relation\' => \'AND\', //Is this "And" my original query, or just "and" these two parameters?
array(
\'taxonomy\' => \'category\',
\'field\' => \'id\',
\'terms\' => 5
),
array(
\'taxonomy\' => \'post_tag\',
\'field\' => \'id\',
\'terms\' => array(5,6,7)
)
);
我更新的WP\\U查询将是:
$args = array(
\'post_type\' => $postType, //assume \'post\'
\'cat\' => $cat_id, //currently a single id
\'tax_query\' => $taxQuery,
\'orderby\' => \'date\',
\'post_status\' => \'publish\',
);
感谢您抽出时间!
SO网友:Edwin Daniels
对我来说,执行AND/或嵌套查询的一种方法是只传递一个值数组。我相信它通过IN(a,b…)隐式地使用列表作为ORMySQL语法。
下面是一个我可以用于分类查询的示例:
// ... Other query params in $query
$query[\'tax_query\'] = [\'relation\' => \'AND\'];
$query[\'tax_query\'][] =[[ \'taxonomy\' => \'field_a\',
\'field\' => \'slug\',
\'terms\' => [\'a\',\'b\',\'c\']]; // this is the "OR"
$query[\'tax_query\'][] =[[ \'taxonomy\' => \'field_b\',
\'field\' => \'slug\',
\'terms\' => [\'d\',\'e\',\'f\']]; // this is the "OR"
$get_posts = new WP_Query;
$posts = $get_posts->query($query);
这实际上会生成一个查询,例如:
field_a IN(\'a\',\'b\',\'c\') AND field_b IN(\'d\',\'e\',\'f\')