你可以使用tax_query
来解决这个问题。
我想4
和6
只是类别,因此您可能需要在$tax_query
数组,而不是声明它,但请告诉我们这是否是一个问题。记住这一点relation => \'AND\'
必须包含。
$tax_query = array(
relation => \'AND\',
array(
\'taxonomy\' => \'category\',
\'field\' => \'term_id\', // \'term_id\' by default, so just here as an example
\'terms\' => $cat,
\'include_children\' => false, // true by defualt
\'operator\' => \'IN\' // \'IN\' by default, so just here as an example
),
array(
\'taxonomy\' => \'category\',
\'terms\' => $cat2,
\'include_children\' => false, // true by defualt
)
)
一旦设置好
$tax_query
根据需要,只需将其添加到查询中,以及所需的任何其他参数,如下所示-
\'tax_query\' => $tax_query
查看类参考
WP_Query
有关更多详细信息-
http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters更新OP建议$cat
实际上可能包含多个类别,而不是仅包含一个类别,因此下面的代码(未测试)应考虑到这一点,同时仍使用查询的“tax\\u query”参数。
/** Ensure that \'$cat\' is cast as an array */
if(!is_array($cat) && !empty($cat))
$cat = explode(\',\', $cat);
/** Ensure that \'$cat2\' is cast as an array */
if(!is_array($cat2) && !empty($cat2))
$cat2 = explode(\',\', $cat2);
/** Create a single array of all categories */
$cats_array = $cat + $cat2
/** Create the \'$tax_query\' variable and cast it as an array */
$tax_query = array();
/** Add each category to the \'tax_query\' */
if(!empty($cats_array)) : foreach($cats_array as $single_cat) :
$tax_query[] = array(
\'taxonomy\' => \'category\',
\'terms\' => $single_cat,
\'include_children\' => false, // true by defualt
)
endforeach;
endif;
/** Check to see if there is more than one category within the \'tax_query\' and if so set the relation to \'AND\' */
if(count($tax_query) > 1)
$tax_query[\'relation\'] = \'AND\';
这里唯一要注意的是你应该检查一下
if(!empty($tax_query))
将其添加到查询之前。
您也可以将此方法用于自定义分类法。