简体   繁体   中英

Exclude specific category in my WooCommerce related products widget

All my WooCommerce products are assigned two categories. 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.

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.

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 . You can use this to remove 'all-products' in the array of categories used to get the 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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