I have a Wordpress website that has a related produts slider when inside a product, the related products slider has a filter to only relate produts by tags instead tags and categories. I want to know if is possible to only have related produts that only match at least 3 tags or more?
In the functions.php of the children theme i have this filter to only filter by tags:
add_filter( 'woocommerce_product_related_posts_relate_by_tag', '__return_false' );
Tested and it works:
add_filter( 'woocommerce_related_products', 'bbloomer_related_products_at_least_3_tags_in_common', 9999, 3 );
function bbloomer_related_products_at_least_3_tags_in_common( $related_posts, $product_id, $args ) {
$tags_array = wc_get_product_term_ids( $product_id, 'product_tag' );
foreach ( $related_posts as $key => $related_post_id ) {
$related_post_tags_array = wc_get_product_term_ids( $related_post_id, 'product_tag' );
if ( count( array_intersect( $tags_array, $related_post_tags_array ) ) < 3 ) unset( $related_posts[$key] );
}
return $related_posts;
}
This basically checks if each related product has at least 3 tags in common with the current product. You can change "3" to whatever number you wish.
Also, please do not use:
add_filter( 'woocommerce_product_related_posts_relate_by_tag', '__return_false' );
Because that will stop comparing products based on tag. You need to use this instead:
add_filter( 'woocommerce_product_related_posts_relate_by_category', '__return_false' );
... so that you don't compare by category, which means products are only compared by tag