WooCommerce - 按产品属性和类别过滤相关产品

发布于 2025-01-13 14:54:55 字数 1066 浏览 0 评论 0原文

我正在寻求调整相关产品,以便它返回与当前产品的颜色和类别相匹配的产品。

我可以让其中之一工作,但不能同时工作。

请参阅下面的代码:

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

耳根太软 2025-01-20 14:54:55

在尝试了很多方法之后,事实证明这就像将产品类别放入查询的第一部分一样简单,如下所示:

'post_type'            => 'product',
'product_cat'          => 'carpet',
'posts_per_page'       => 4,
'post__not_in'         => array( $product_id ),
'tax_query'            => array( 

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:

'post_type'            => 'product',
'product_cat'          => 'carpet',
'posts_per_page'       => 4,
'post__not_in'         => array( $product_id ),
'tax_query'            => array( 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文