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

WooCommerce单商品页如何获取当前唯一选中的产品分类名称

WooCommerce单商品页获取唯一产品分类名称解决方案

你原有代码中直接输出get_the_terms返回值的写法错误,该函数返回的是分类术语对象数组,无法直接转为字符串输出。由于你站点每个商品仅归属一个产品分类,直接提取数组第一个元素的名称属性即可实现需求。

可用实现代码

直接替换你现有<!-- Get Woocommerce product category -->注释下方的代码段即可:

<!-- Get Woocommerce product category -->        
<?php
// 获取当前商品关联的产品分类
$product_cats = get_the_terms( get_the_ID(), 'product_cat' );
// 异常判断避免数据为空时报错
if ( $product_cats && ! is_wp_error( $product_cats ) ) {
    // 取唯一分类的名称输出
    $cat_name = reset( $product_cats )->name;
    ?>
    <span class="property-type-badge"><?php echo esc_html( $cat_name ); ?></span>
    <?php
}
?>

代码说明

  • 用get_the_ID()获取当前商品ID,兼容性比直接调用$post->ID更高,不需要额外声明全局$post变量
  • 内置错误判断逻辑,即使分类数据异常也不会导致页面崩溃
  • 输出前加了esc_html()做内容转义,符合WordPress编码安全规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:45:02