首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Woocommerce:产品页面上其他类别的产品(交叉产品)

Woocommerce:产品页面上其他类别的产品(交叉产品)
EN

Stack Overflow用户
提问于 2021-12-17 08:58:46
回答 1查看 53关注 0票数 -2

例如,有一个类别层次结构。

代码语言:javascript
复制
cat_1
- cat_1_1
- cat_1_2

cat_2
- cat_2_1
- cat_2_2

etc...

我想在产品页面上显示不包括此产品的其他类别的产品。

例如,如果该产品属于cat_1_1类别,则有必要:

由父类获取当前产品类别(cat_1_1);

  • Get整个类别树,其中包括来自任何类别的任何产品的第1 (cat_1, cat_1_1, cat_1_2);

  • Show 5段接收的类别,但第2段中收到的产品除外。

类似于基于类别的交叉销售。

我想我无意中找到了正确的解决方案here,但在我的例子中,由于某种原因,它返回所有类别而不排除当前产品的类别树。

代码语言:javascript
复制
$current_term = get_queried_object(); // Already a WP_Term Object

if ( $current_term->parent > 0 ) {
    $siblings_ids = get_terms( array(
        'taxonomy'  => 'product_cat',
        'parent'    => $current_term->parent,
        'exclude'   => $current_term->term_id,
        'fields'    => 'ids',
    ) );

    // Get a string of coma separated terms Ids
    $siblings_list_ids = implode(',', $siblings_ids);

    // Testing output
    echo $siblings_list_ids;
}

我会感谢你的帮助)

EN

回答 1

Stack Overflow用户

发布于 2021-12-17 09:33:53

您必须获得当前的产品术语,因此您可以使用get_the_terms()函数。然后可以使用tax_query排除该类别产品。试试下面的代码。

代码语言:javascript
复制
global $post;

$ids = array();

// Get the product categories
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ){
    $ids[] = $term->term_id; // add term id to an array.
}

// The Query    
$category_based_cross_selling = new WP_Query( array(
    'post_type' => 'product',
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field'    => 'term_id',
            'terms'    => $ids,
            'operator' => 'NOT IN'
        ),
    ),
) );

$postIds = array();

if ( $category_based_cross_selling->have_posts() ): 
    while ( $category_based_cross_selling->have_posts() ) : $category_based_cross_selling->the_post();
       
    endwhile;
endif;

wp_reset_query();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70390631

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档