英文:
WordPress Related Products have to match at least 3 tags
问题
我有一个WordPress网站,在产品页面内有一个相关产品幻灯片,该幻灯片具有一个筛选器,只使用标签而不是标签和类别来关联产品。
我想知道是否可能只有相关产品,这些产品至少匹配3个或更多的标签?
在子主题的functions.php文件中,我有以下筛选器,只筛选标签:
add_filter( 'woocommerce_product_related_posts_relate_by_tag', '__return_false' );
英文:
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' );
答案1
得分: 1
已测试,可以正常工作:
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;
}
这基本上是检查每个相关产品是否与当前产品至少有3个共同的标签。您可以将“3”更改为您希望的任何数字。
另外,请不要使用:
add_filter('woocommerce_product_related_posts_relate_by_tag', '__return_false');
因为这将停止基于标签比较产品。您需要使用这个代替:
add_filter('woocommerce_product_related_posts_relate_by_category', '__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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论