WooCommerce: Get Related Products by Attribute

Date: 
1. November 2021
Author: 
mbs
Category: 
  1. Open Single Product Template in Oxygen and Add "Product builder"
  2. Add "Related products"
  3. Save

Then add this code snippet to your favorite code operator, and remember to change pa_attribute-insert-here

Love to all the Oxygen team (Mostly Phe...) for helping with this

add_filter( 'woocommerce_related_products', 'related_products_by_attribute', 10, 3 );
function related_products_by_attribute( $related_posts, $product_id, $args ) {
    $taxonomy   = 'pa_attribute-insert-here'; // HERE define the targeted product attribute taxonomy

    $term_slugs = wp_get_post_terms( $product_id, $taxonomy, ['fields' => 'slugs'] ); // Get terms for the product

    if ( empty($term_slugs) )
        return $related_posts;

    $posts_ids = get_posts( array(
        'post_type'            => 'product',
        'ignore_sticky_posts'  => 1,
        'posts_per_page'       => 4,
        'post__not_in'         => array( $product_id ),
        'tax_query'            => array( array(
            'taxonomy' => $taxonomy,
            'field'    => 'slug',
            'terms'    => $term_slugs,
        ) ),
        'fields'  => 'ids',
        'orderby' => 'rand',
    ) );

    return count($posts_ids) > 0 ? $posts_ids : $related_posts;
}

Leave a Reply

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

© Copyright 2007-2024
mbsTECH.dk

Build with
and 
Oxygenbuilder
I'm using 
Ahoy