'WooCommerce - Filtering related products by product attribute and category

I'm looking to adapt the related products so that it returns products that match the colour and category of the current product.

I can get one or the other working, but not both.

Please see code below:

$attribute   = 'pa_colour';

$term_slugs = wp_get_post_terms( $product_id, $attribute, ['fields' => 'slugs'] );

$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
    $product_cat_id = $term->term_id;
    break;
}

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

$new_relations = get_posts( array(
    'post_type'            => 'product',
    'posts_per_page'       => 4,
    'post__not_in'         => array( $product_id ),
    'tax_query'            => array( 
        'relation' => 'AND',
        array(
            'taxonomy' => $attribute,
            'field'    => 'slug',
            'terms'    => $term_slugs,
        ),
        array(
            'taxonomy' => 'product_cat',
            'field'    => 'slug',
            'terms'    => $product_cat_id,
        ),
    ),
    'fields'  => 'ids',
    'orderby' => 'rand',
) );

If anyone can point me in the right direction, that would be great.

Thanks



Solution 1:[1]

After trying many things, it turns out it's as simple as dropping the product category into the first part of the query like so:

'post_type'            => 'product',
'product_cat'          => 'carpet',
'posts_per_page'       => 4,
'post__not_in'         => array( $product_id ),
'tax_query'            => array( 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Johnny