简体   繁体   English

在我的 WooCommerce 相关产品小部件中排除特定类别

[英]Exclude specific category in my WooCommerce related products widget

All my WooCommerce products are assigned two categories.我所有的 WooCommerce 产品都被分配了两个类别。 The first category is called "All Products", which all products get assigned.第一个类别称为“所有产品”,所有产品都被分配。 The second category is dependent on the product, it could be Movies, Books, Tools, etc.第二个类别取决于产品,可能是电影、书籍、工具等。

Since every product is assigned the "All Products" category, in the related products widget on the product page, you see every product, instead of just the second (more specific) category of products.由于每个产品都被分配了“所有产品”类别,因此在产品页面上的相关产品小部件中,您可以看到每个产品,而不仅仅是第二个(更具体的)产品类别。

I am trying to add some code in functions.php that will ignore "All Products" as a category for the related products widget, but still show the related products for the second category of which the product is assigned.我试图在functions.php 中添加一些代码,这些代码将忽略“所有产品”作为相关产品小部件的类别,但仍显示分配了产品的第二个类别的相关产品。

So far I have this code, which hides the related products widget all-together.到目前为止,我有这段代码,它将相关产品小部件隐藏在一起。 I think this is because every product is assigned the slug 'all-products', so it removes the widget instead of counting for the second category that the product is assigned.我认为这是因为每个产品都被分配了 slug 'all-products',所以它删除了小部件而不是计算分配给产品的第二个类别。

add_filter( 'woocommerce_related_products', 'exclude_product_category_from_related_products', 10, 3 );
function exclude_product_category_from_related_products( $related_posts, $product_id, $args  ){
    // HERE define your product category slug
    $term_slug = 'all-products';

    // Get the product Ids in the defined product category
    $exclude_ids = wc_get_products( array(
        'status'    => 'publish',
        'limit'     => -1,
        'category'  => array($term_slug),
        'return'    => 'ids',
    ) );

    return array_diff( $related_posts, $exclude_ids );
}

How can I edit this code so that it will hide the 'all-products' category from showing in the related products, but still show the other assigned category's related products?如何编辑此代码,使其隐藏“所有产品”类别,使其不显示在相关产品中,但仍显示其他指定类别的相关产品?

You're better off with woocommerce_get_related_product_cat_terms .你最好使用woocommerce_get_related_product_cat_terms You can use this to remove 'all-products' in the array of categories used to get the products.您可以使用它来删除用于获取产品的类别数组中的'all-products'

add_filter( 'woocommerce_get_related_product_cat_terms', 'exclude_product_category_from_related_products' );
function exclude_product_category_from_related_products( $cats_array ) {

    $term = get_term_by('slug', 'all-products', 'product_cat');

    if ( $term && ($key = array_search($term->term_id, $cats_array)) !== false) {
        unset($cats_array[$key]);
    }

    return $cats_array;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM