WP_QUERY参数添加多个TAX_QUERY

时间:2014-10-01 作者:Ryan Bowden

我正在创建一个自定义搜索系统来搜索我的自定义帖子类型食谱,在搜索中它搜索人们选择的分类术语。

现在,由于它可以硬编码所有这些,我需要通过某种循环来构建args。

下面是一个代码示例,

$args = array(
\'post_type\'      => get_post_type(),
\'orderby\'        => \'menu_order\',
\'order\'          =>  \'ASC\',
\'posts_per_page\' => -1,
\'no_found_rows\'  => true,
\'tax_query\' => array(
    \'relation\' => \'AND\',
    array(
        \'taxonomy\' => \'product_category\',
        \'field\'    => \'slug\',
        \'terms\'    => array($category->slug), //Supply the current product_category terms
    ),
    array(
        \'taxonomy\' => \'product_locations\',
        \'field\'    => \'slug\',
        \'terms\'    => array($current_location), //Add the product_locations term
        \'operator\' => \'IN\',
    ),
),
);
我需要补充的是:

array(
        \'taxonomy\' => \'product_category\',
        \'field\'    => \'slug\',
        \'terms\'    => array($category->slug), //Supply the current product_category terms
    ),
我需要的是,当有人选择时,以编程方式添加它们。我曾尝试使用循环构建args数组,并将字符串添加到一起,但我无法使其工作。有没有人有什么快速的方法可以做到这一点?

1 个回复
最合适的回答,由SO网友:Domain 整理而成

可以使用IF条件添加参数,

$args = array(
\'post_type\'      => get_post_type(),
\'orderby\'        => \'menu_order\',
\'order\'          =>  \'ASC\',
\'posts_per_page\' => -1,
\'no_found_rows\'  => true,
\'tax_query\' => array(),
);

if(condition){
    $args[\'tax_query\'] = array(
        \'relation\' => \'AND\',
        array(
            \'taxonomy\' => \'product_category\',
            \'field\'    => \'slug\',
            \'terms\'    => array($category->slug), //Supply the current product_category terms
        ),
        array(
            \'taxonomy\' => \'product_locations\',
            \'field\'    => \'slug\',
            \'terms\'    => array($current_location), //Add the product_locations term
            \'operator\' => \'IN\',
        ),
    ),
}
else{
     $args[\'tax_query\'] = array(
        array(
            \'taxonomy\' => \'product_category\',
            \'field\'    => \'slug\',
            \'terms\'    => array($category->slug), //Supply the current product_category terms
        ),
     );
}

结束

相关推荐

Primary Taxonomy for Post

我的博客帖子附带了多个自定义分类法中的项目。为了这篇文章的缘故,让我们只使用标记分类法。。。所以一篇文章可能包含4个标签,有没有办法选择一个标签作为文章的主要标签?