WP SITES

3086 Coded Tutorials & 288 Plugins

Show Related Products from Same Product Subcategory in WooCommerce

There’s at least 2 methods you can use to make sure your related products from the same product child category are displayed on your single product pages using WooCommerce.

The 1st method involved removing the default related products function and then adding back a custom function which includes the woocommerce_related_products function with the category__in parameter with a value for the $subcategories variable.

Here’s the code for the first solution you can add to your child themes functions file or custom code snippets plugin.

remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );

add_action( 'woocommerce_after_single_product_summary', function() {
    global $product;
    
    $terms = get_the_terms( $product->get_id(), 'product_cat' );
    if ( empty( $terms ) || is_wp_error( $terms ) ) {
        return;
    }

    $subcategories = array();
    foreach ( $terms as $term ) {
        if ( $term->parent != 0 ) {
            $subcategories[] = $term->term_id;
        }
    }

    if ( empty( $subcategories ) ) {
        return;
    }

    woocommerce_related_products( array(
        'posts_per_page' => 4,
        'columns'        => 4,
        'orderby'        => 'rand',
        'category__in'   => $subcategories,
    ) );
}, 20 );

The 2nd solution involves filtering the default wc_get_related_products function which includes a filter hook named woocommerce_related_products and adding a tax_query to the arguments which includes subcategories to change the default value for the $related_posts variable. This function is included in the default woocommerce_related_products function in WooCommerce.

add_filter( 'woocommerce_related_products', function( $related_posts, $product_id ) {
    $product = wc_get_product( $product_id );
    $terms = get_the_terms( $product_id, 'product_cat' );

    if ( empty( $terms ) || is_wp_error( $terms ) ) {
        return $related_posts;
    }

    $subcategories = array_map( function( $term ) {
        return $term->term_id;
    }, $terms );

    $args = [
        'post_type'      => 'product',
        'posts_per_page' => apply_filters( 'woocommerce_output_related_products_args', [ 'posts_per_page' => 4 ] )['posts_per_page'],
        'post__not_in'   => [ $product_id ],
        'orderby'        => 'rand',
        'tax_query'      => [
            [
                'taxonomy' => 'product_cat',
                'field'    => 'term_id',
                'terms'    => $subcategories,
            ],
        ],
    ];

    $query = new WP_Query( $args );
    return wp_list_pluck( $query->posts, 'ID' );
}, 10, 2 );

There are other methods to display products from child categories as related products however these are the 2 best and the 2nd solution is the most efficient.

Not exactly what you’re looking for?

Get Help

Leave a Reply

New Plugins