如何解决在WooCommerce中使用AND关系查询2个类别词的纳税查询
我想获得我所有属于A + B类的产品,我使用tax_query进行了尝试,但是直到现在我还没有得到预期的结果。
$args = array(
'posts_per_page' => -1,'post_type' => 'product','tax_query' => array(
'relation' => 'AND',array(
'taxonomy' => 'product_cat','field' => 'term_id','terms' => $_GET["terms"],)
),);
通过该查询,我得到A或B中的产品...
解决方法
已更新
假设传递的url参数有点像?terms[0]=15&terms[1]=22
(其中15
和22
是ID),所以$_GET["terms"]
给出了一组术语ID,那么您将使用以下代码:
$tax_query = array(); // Initializing
if( isset($_GET['terms']) && is_array($_GET['terms']) ) {
$terms_ids = wc_clean($_GET['terms']);
$tax_query = count($terms_ids) > 1 ? array('relation' => 'AND') : array();
// Loop through terms Ids
foreach( $terms_ids as $term_id ) {
$tax_query[] = array(
'taxonomy' => 'product_cat','field' => 'term_id','terms' => $term_id,);
}
}
$args = array(
'posts_per_page' => -1,'post_type' => 'product','post_status' => 'publish','tax_query' => $tax_query
);
经过测试可以正常工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。