我想在tax\\u查询[\'terms\']为空时返回所有帖子。
$args = array(
\'post_type\' => \'product\',
\'posts_per_page\' => 15,
\'paged\' => $paged,
\'post__not_in\' => $exclude,
\'s\' => $filter,
\'tax_query\' => array(
array(
\'taxonomy\' => \'product_cat\',
\'field\' => \'term_id\',
\'terms\' => array(),
),
),
);
不幸的是,我没有找到解决问题的办法。如您所见,阵列为空:
\'terms\' => array(),
但我想退回所有帖子。我怎样才能做到这一点?
最合适的回答,由SO网友:Pieter Goosen 整理而成
正如@Milo已经暗示的那样,在附加tax_query
您可以尝试以下操作:(由于数组语法较短,需要PHP 5.4+,如有必要,请还原为旧语法)
$args = [
\'post_type\' => \'product\',
\'posts_per_page\' => 15,
\'paged\' => $paged,
\'post__not_in\' => $exclude,
\'s\' => $filter,
];
// Append our tax-query if we have terms. Make sure it is a valid string or array
$term = \'DEFINE YOUR TERM HERE\';
if ( $terms ) {
$args[\'tax_query\'] = [
[
\'taxonomy\' => \'product_cat\'
\'terms\' => $terms,
]
];
}
$q = new WP_Query( $args );