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

仅通过产品ID能否获取Yoast主分类?已尝试指定代码无效

通过产品ID获取Yoast WooCommerce产品主分类

你的代码思路方向正确,但可能因Yoast版本迭代、函数未加载或参数场景问题导致失效。以下是几种可靠的解决方法:

方法一:兼容旧版Yoast的函数调用

先确认yoast_get_primary_term_id函数存在(部分新版本Yoast已逐步弃用该函数),再结合有效性检查调用:

// 先验证函数是否存在
if ( function_exists( 'yoast_get_primary_term_id' ) ) {
    $primary_term_id = yoast_get_primary_term_id( 'product_cat', $product->get_id() );
    // 确保获取到有效分类ID
    if ( ! empty( $primary_term_id ) ) {
        $primary_term = get_term( $primary_term_id, 'product_cat' );
        // 示例:输出主分类名称
        echo $primary_term->name;
    }
}

方法二:新版Yoast推荐的类调用

Yoast官方现在更推荐使用WPSEO_Primary_Term类,兼容性更强:

// 验证类是否存在
if ( class_exists( 'WPSEO_Primary_Term' ) ) {
    $primary_term_handler = new WPSEO_Primary_Term( 'product_cat', $product->get_id() );
    $primary_term_id = $primary_term_handler->get_primary_term();
    
    if ( ! empty( $primary_term_id ) ) {
        $primary_term = get_term( $primary_term_id, 'product_cat' );
        // 按需处理分类数据,比如获取slug或链接
        echo $primary_term->slug;
    }
}

方法三:直接读取Yoast存储的元数据

Yoast会将主分类ID存在产品的元字段_yoast_wpseo_primary_product_cat中,可直接读取作为兜底方案:

$primary_term_id = get_post_meta( $product->get_id(), '_yoast_wpseo_primary_product_cat', true );
if ( ! empty( $primary_term_id ) ) {
    $primary_term = get_term( $primary_term_id, 'product_cat' );
    echo $primary_term->name;
}

常见排查点

  • 确认Yoast SEO插件已激活并正常运行
  • 目标产品确实设置了Yoast主分类(未设置时所有方法都会返回空)
  • 确保代码在产品上下文执行(比如产品页面、产品循环内),或直接传入产品ID数值(如123代替$product->get_id())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 18:55:26