skip to Main Content

If you want to only show products from the last category inside your WooCommerce related products section, then place the code below into your functions.php.

add_filter( 'woocommerce_get_related_product_cat_terms', 'last_child_cats_only', 10, 2 );
function last_child_cats_only( $term_ids, $product ) {
	
	if(!$product) {
		return $term_ids;
	}

    $cats_array = array();
    $terms = wp_get_post_terms($product, 'product_cat');
    foreach ( $terms as $key => $term ){
        $check_for_children = get_categories(array('parent' => $term->term_id, 'taxonomy' => 'product_cat'));
        if(empty($check_for_children)){
            $cats_array[] = $term->term_id;
        }
    }

    if(!empty($cats_array)) {
    	$term_ids = $cats_array;
    }

   	return $term_ids;

}

Daniel Barenkamp

Founder and Creator of WeLaunch (formerly DB-Dzine).

This Post Has 0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×Close search
Search