我试图根据表单输入字段创建一个简单的表单来查询woocommerce产品wine,如下所示:
按类别和价格过滤,但标签给出了混合的结果,我无法弄清楚原因。
这就是我的表单看起来如何给出一些上下文:
这是我的代码:
$custom_query_args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'order' => 'DESC',
'posts_per_page' => 3,
'product_tag' => array($tag1, $tag2, tag3),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => array( esc_attr( $category ) ),
'field' => 'slug',
'operator' => 'OR'
)),
//Price
'meta_query' => array(
array(
'key' => '_price',
'value' => array($clow, $chigh),
'compare' => 'BETWEEN',
'type' => 'NUMERIC'
)
)
);
从输入字段,我有3个产品标签变量(如$tag1
,$tag2
,$tag3
),1个产品类别变量(如$category
)和价格范围的2个变量(如$clow
和$chigh
),它们是来自的价格。
任何人都知道为什么会这样?
你的代码中有一些小错误:
$
缺少tag3
,OR
不是operator
值(并且不需要),tax_query
阵列中,以使您的过滤器正常工作。因此,请尝试以下修改后的代码:
$custom_query_args = array(
'posts_per_page' => 3,
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'order' => 'DESC',
'tax_query' => array(
// Product category filter
array(
'taxonomy' => 'product_cat',
'terms' => array( esc_attr( $category ) ),
'field' => 'slug',
),
// Product tag 1 filter
array(
'taxonomy' => 'product_tag',
'terms' => array($tag1),
'field' => 'slug',
),
// Product tag 2 filter
array(
'taxonomy' => 'product_tag',
'terms' => array($tag2),
'field' => 'slug',
),
// Product tag 3 filter
array(
'taxonomy' => 'product_tag',
'terms' => array($tag3),
'field' => 'slug',
),
),
// Price filter
'meta_query' => array( array(
'key' => '_price',
'value' => array($clow, $chigh),
'compare' => 'BETWEEN',
'type' => 'NUMERIC'
) ),
);
经过测试和工作。
我找到了更简单的方法来做到这一点,它更好,因为当没有过滤器时,它将显示所有产品,查询也更小,如下所示:
$category = 'category-slug-here'; //String, but can accept array?
$tags = 'comma,delimeted,tags,here'; //I build string with tags needed no array.
$clow = 0; //min price int
$chigh = 200; //max price int
$custom_query_args = array(
'posts_per_page' => '12',
'product_cat' => $category,
'post_type' => 'product',
'product_tag' => $tags,
// Price filter
'meta_query' => array( array(
'key' => '_price',
'value' => array($clow, $chigh),
'compare' => 'BETWEEN',
'type' => 'NUMERIC'
) ),
);
是否有任何不好的方面这样做,因为我已经使用不同的过滤器标签测试它,它像我计划的那样工作?