Search code examples
phpwordpresswoocommerceproducttaxonomy-terms

Exclude a product category from Woocommerce related products


In woocommerce, I am trying to remove a specific product category from displayed related products on single product pages.

I have tried to use a function hooked in woocommerce_get_related_product_cat_terms, filter hook, like in some answer threads, but it doesn't seem to work anymore.

How to exclude a specific product category from Woocommerce related products?


Solution

  • Try woocommerce_related_products hook in the following hooked function, to exclude a specific product category from displayed related 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 = 'hoodies';
    
        // 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 );
    }
    

    Code goes in function.php file of the active child theme (or active theme).

    Tested and works.

    Related answer thread: Exclude related products ids in Woocommerce