WooCommerce, limit related products to have the same developer
/* Show related products only for same developer */
add_filter( 'woocommerce_related_products', 'web_related_products_by_attribute', 10, 3 );
function web_related_products_by_attribute( $related_posts, $product_id, $args ) {
$taxonomy = 'pa_developer'; // here we 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( [
'post_type' => 'product',
'ignore_sticky_posts' => 1,
'posts_per_page' => 4,
'post__not_in' => [$product_id],
'tax_query' => [
'relation' => 'AND',
[
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $term_slugs
],
[
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => wc_get_product_term_ids( $product_id, 'product_cat' ),
]
],
'fields' => 'ids',
'orderby' => 'rand',
]
);
return count($posts_ids) > 0 ? $posts_ids : $related_posts;
}