You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改WooCommerce代码实现基于自定义taxonomy「sport」关联商品

适配自定义分类「sport」的Rank Math关联商品筛选代码

以下是调整后的代码,替换原有的product_cat逻辑,适配自定义分类「sport」:

add_filter( 'rank_math/related_posts/args', 'custom_rank_math_related_sport_products', 10, 2 );
function custom_rank_math_related_sport_products( $args, $post ) {
    // 仅对商品类型生效
    if ( 'product' !== get_post_type( $post ) ) {
        return $args;
    }

    // 获取当前商品关联的「sport」分类项
    $sport_terms = get_the_terms( $post->ID, 'sport' );
    if ( empty( $sport_terms ) || is_wp_error( $sport_terms ) ) {
        return $args;
    }

    // 提取分类ID数组
    $sport_term_ids = wp_list_pluck( $sport_terms, 'term_id' );

    // 构建分类查询,筛选共享同一sport分类的商品
    $args['tax_query'] = array(
        array(
            'taxonomy' => 'sport',
            'field'    => 'term_id',
            'terms'    => $sport_term_ids,
            'operator' => 'IN',
        )
    );

    // 排除当前商品本身
    $args['post__not_in'] = array( $post->ID );

    return $args;
}

关键调整说明

  • 限定生效范围:增加商品类型判断,避免对非商品内容产生影响
  • 正确获取自定义分类:使用get_the_terms()明确指定sport分类,确保能拿到当前商品关联的自定义分类项
  • 修正分类查询参数:精准设置tax_query的taxonomy为sport,用分类ID进行匹配
  • 排除当前商品:添加post__not_in参数,防止关联列表出现当前商品

故障排查点

如果代码仍失效,检查以下内容:

  • 确认自定义分类sport注册时已关联product类型(注册代码中需包含'object_type' => array( 'product' ))
  • 确保当前商品已关联至少一个sport分类项
  • 检查Rank Math后台设置,确认「相关产品」功能已开启,且无其他优先级更高的筛选规则

内容的提问来源于stack exchange,提问作者quizzical

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 19:50:58