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

如何让WooCommerce按Rank Math主分类或单一分类显示关联商品

解决WooCommerce关联商品仅显示Rank Math主分类(兼容单分类场景)

以下是修改后的代码,新增了单分类场景的兼容逻辑:

/* Rank Math SEO - Use Primary Category for Related Products (with single category fallback) */
function related_products_from_rank_math_primary_category( $related_posts, $product_id, $args  ) {
    // 先尝试获取Rank Math设置的主分类ID
    $primary_cat_id = get_post_meta( $product_id, 'rank_math_primary_product_cat', true );

    // 如果主分类不存在(比如商品仅属于单个分类时),获取商品的第一个产品分类
    if ( empty( $primary_cat_id ) ) {
        $product_cats = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'ids' ) );
        if ( ! empty( $product_cats ) ) {
            $primary_cat_id = reset( $product_cats );
        }
    }

    // 如果仍未获取到有效分类ID,返回原关联商品列表
    if ( empty( $primary_cat_id ) ) {
        return $related_posts;
    }

    // 获取分类信息及slug
    $primary_cat_info = get_term_by( 'id', $primary_cat_id, 'product_cat' );
    if ( ! $primary_cat_info ) {
        return $related_posts;
    }
    $primary_cat_slug = $primary_cat_info->slug;

    // 获取该分类下的关联商品(排除当前商品)
    $args = array(
        'status'            => 'publish',
        'category'          => array( $primary_cat_slug ),
        'return'            => 'ids',
        'exclude'           => array( $product_id ),
        'visibility'        => 'catalog',
        'posts_per_page'    => -1,
    );
    $related_posts = wc_get_products( $args );

    return $related_posts;
}
add_filter( 'woocommerce_related_products', 'related_products_from_rank_math_primary_category', 10, 3 );

关键逻辑说明

  • 优先读取Rank Math设置的主分类ID,保证多分类场景下的原有逻辑
  • 当主分类ID为空时,通过wp_get_post_terms获取商品所属的所有产品分类,取第一个分类ID(单分类场景下即为唯一分类)
  • 增加了分类有效性校验,避免因无效分类ID导致的报错
  • 若最终未获取到任何有效分类ID,会返回WooCommerce默认的关联商品列表,保证兼容性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:05:11