我正在创建一个自定义搜索系统来搜索我的自定义帖子类型食谱,在搜索中它搜索人们选择的分类术语。
现在,由于它可以硬编码所有这些,我需要通过某种循环来构建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数组,并将字符串添加到一起,但我无法使其工作。有没有人有什么快速的方法可以做到这一点?
最合适的回答,由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
),
);
}