Remove parent categories from WooCommerce Related Products

Say you are selling Phones, Tablets, Smart Watches etc. – and all of those are children of parent category called Gadgets. In this case you have probably faced non-relevant related-products in product-single page of your WooCommerce website.

So, the idea is this: To remove parent categories from related-categories algorithm and to force WooCommerce to show related categories by last child category only (tablets for a tablet, phones for a phone etc. not tablets for a phone)

So let’s write small snippet for this:

add_filter( 'woocommerce_get_related_product_cat_terms',
  function($termids,$product_id){
    if(count($termids)<=1)return $termids;
    $childonlys=[];
    foreach($termids as $carr){
        $termcheck=get_term_by('ID',$carr,'product_cat');
        if($termcheck->parent==0)continue;
        $childonlys[]=$carr;
    }
    return  $childonlys;
  },10,2
);

As you can see from the snippet, it gets all categories of the current product, checks each one whether it is parent or child product, if it is a parent product, then it removes parent product category from related product categories and keeps the most relevant onspare only.

What if the website is using multi-level hierarchy, not just 2-level?

For that case we can improve our code by checking all parent IDs of categories:

add_filter( 'woocommerce_get_related_product_cat_terms',
  function($termids,$product_id){
    if(count($termids)<=1)return $termids;
    $childonlys=[];$termcheck=[];$parents=[];
    foreach($termids as $carr){
        $termcheck[$carr]=get_term_by('ID',$carr,'product_cat');
        $parents[]=$termcheck->parent;
    }
    foreach($termcheck as $key=>$value){
        if($value->parent==0 
           or in_array($key,$parents))
           continue;
        $childonlys[]=$key;
    }
    return  $childonlys;
  },10,2
);

Note that the changes will not take an effect immediately – because WooCommerce uses transient cache for related products block – so check back it in few hours after adding this snippet.

Get more useful WP tricks and snippets by subscribing to my mailclub.

2 Replies to “Remove parent categories from WooCommerce Related Products”

  1. It’s working but has one problem, If we open a sub-category product then it’s not showing any product in the related products section. Now what is the solution?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.