为WooCommerce关联商品实现Rank Math主分类优先+子分类降级逻辑
WooCommerce关联商品分类逻辑整合解决方案
直接用钩子替换逻辑,不用修改related.php模板,完美整合原Rank Math主分类逻辑和单分类降级到子分类的需求,代码如下:
add_filter( 'woocommerce_get_related_product_cat_terms', 'custom_related_product_categories', 10, 2 ); function custom_related_product_categories( $category_ids, $product ) { // 获取商品所有产品分类(排除标签) $product_categories = get_the_terms( $product->get_id(), 'product_cat' ); if ( empty( $product_categories ) ) { return $category_ids; } // 多分类场景:用Rank Math主分类 if ( count( $product_categories ) >= 2 ) { $primary_cat_id = get_post_meta( $product->get_id(), 'rank_math_primary_category', true ); if ( ! empty( $primary_cat_id ) && term_exists( $primary_cat_id, 'product_cat' ) ) { return array( intval( $primary_cat_id ) ); } } // 单分类场景:降级到子分类 else { $current_cat = reset( $product_categories ); // 获取该分类的直接子分类 $child_cats = get_terms( array( 'taxonomy' => 'product_cat', 'parent' => $current_cat->term_id, 'hide_empty' => true, ) ); if ( ! empty( $child_cats ) ) { $child_cat_ids = wp_list_pluck( $child_cats, 'term_id' ); return $child_cat_ids; } } // fallback:如果以上逻辑都不触发,返回原分类ID return wp_list_pluck( $product_categories, 'term_id' ); }
代码说明:
- 钩子
woocommerce_get_related_product_cat_terms直接干预WooCommerce获取关联商品的分类依据,不会和模板修改冲突 - 多分类时优先读取Rank Math设置的主分类ID,确保原逻辑正常运行
- 单分类时自动检测该分类的子分类,有子分类就用子分类拉取关联商品;如果没有子分类,就默认用原分类
- 所有判断都做了空值校验,避免报错
使用方法:把这段代码复制到你的主题functions.php文件末尾,或者放到自定义功能插件里即可生效,无需修改任何WooCommerce模板文件。
内容的提问来源于stack exchange,提问作者JapeNZ
相关产品推荐
相关产品推荐

