I have found this snippet for showing related products from the primary category.

 // Alter related products query to pull items from Yoast Primary Category
 add_filter( 'woocommerce_get_related_product_cat_terms', function( $terms, $product_id ) {
    if ( function_exists( 'yoast_get_primary_term_id' ) ) {
        $primary_term_product_id = yoast_get_primary_term_id( 'product_cat', $product_id );
        if ( $primary_term_product_id ) {
            return array( $primary_term_product_id );
    return $terms;
 }, 10, 2 );

And it looks like it's working for the first main category, but what if I have a sub-category for my products, then it's not working.

Anyone can help to make it look for both main and sub-category if it's a primary category.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.