Well, it's not that simple using the related products functionality itself, but here is my code that selects related products by category + by color (product attribute). I have replaced default related products loop with a [product]
shortcode. It's not perfect, but it works.
First of all you need a function that returns term slugs by specified taxonomy and product id. I have just tweaked native WooCommerce function wc_get_product_term_ids
public function my_get_product_term_slugs( $product_id, $taxonomy ) {
$terms = get_the_terms( $product_id, $taxonomy );
return ( empty( $terms ) || is_wp_error( $terms ) ) ? array() : wp_list_pluck( $terms, 'slug' );
}
Then I have used this function inside the main function that returns the product shortcode.
function my_get_custom_related_products( $product, $limit = 4 ) {
$product_id = $product->get_id();
$categories = implode( ', ', my_get_product_term_slugs( $product_id, 'product_cat' ) );
$colors = implode( ', ', my_get_product_term_slugs( $product_id, 'pa_color' ) );
return do_shortcode( '[products attribute="color" terms="' . $colors . '" category="' . $categories . '" orderby="rand" limit="' . $limit . '"]' );
}
And then you call this function (with echo) on anywhere you want. I have replaced the related loop with this function. I also used orderby="rand"
inside that [product]
shortcode, to get random results after every reload. Of course you can move the the attribute taxonomy name to function parameters to have more control, but I hope this will help you.
I have tried to somehow tweak the native WC related products query, but it was time consuming so I have decided to go with the shortcode approach.