Start a project
WooCommerce

Show only last WooCommerce category products in related section

· by Daniel

Show only last WooCommerce category products in related section

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;
}

More articles

All articles →
WooCommerceOctober 29, 2026 EmpCo Directive: What Online Shops Must Know About Green Claims Since 27 September 2026 “Sustainable”, “climate-neutral shipping”, “eco-friendly packaging”: claims like these appear in many online shops – in product texts, banners, badges in the footer or in carbon of… WooCommerceDecember 22, 2023 Prevent WP Rocket from Caching Filtered WooCommerce pages When using WP Rocket with preloading in combination with a filter plugin like Filter Everything pro, then your database AND cache folder can explode. We had a site with only around… WooCommerceApril 20, 2022 How to Reactivate old WooCommerce PayPal Standard Gateway WooCommerce has replaced the old PayPal Standard Payment Gateway since version 5.5.

Let's increase your online sales.

Tell us about your shop or website. A developer replies, not a sales team.

★ 4.85/5 from 800+ ratings · Envato Elite Author · Made in Germany