WooCommerce - 按产品属性和类别过滤相关产品
我正在寻求调整相关产品,以便它返回与当前产品的颜色和类别相匹配的产品。
我可以让其中之一工作,但不能同时工作。
请参阅下面的代码:
$attribute = 'pa_colour';
$term_slugs = wp_get_post_terms( $product_id, $attribute, ['fields' => 'slugs'] );
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
break;
}
if ( empty($term_slugs) )
return $related_posts;
$new_relations = get_posts( array(
'post_type' => 'product',
'posts_per_page' => 4,
'post__not_in' => array( $product_id ),
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => $attribute,
'field' => 'slug',
'terms' => $term_slugs,
),
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $product_cat_id,
),
),
'fields' => 'ids',
'orderby' => 'rand',
) );
如果有人能指出我正确的方向,那就太好了。
谢谢
I'm looking to adapt the related products so that it returns products that match the colour and category of the current product.
I can get one or the other working, but not both.
Please see code below:
$attribute = 'pa_colour';
$term_slugs = wp_get_post_terms( $product_id, $attribute, ['fields' => 'slugs'] );
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
break;
}
if ( empty($term_slugs) )
return $related_posts;
$new_relations = get_posts( array(
'post_type' => 'product',
'posts_per_page' => 4,
'post__not_in' => array( $product_id ),
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => $attribute,
'field' => 'slug',
'terms' => $term_slugs,
),
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $product_cat_id,
),
),
'fields' => 'ids',
'orderby' => 'rand',
) );
If anyone can point me in the right direction, that would be great.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在尝试了很多方法之后,事实证明这就像将产品类别放入查询的第一部分一样简单,如下所示:
After trying many things, it turns out it's as simple as dropping the product category into the first part of the query like so: