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;
}
Liked this article? Please follow me on TwitterFollow @baysorensen