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

WooCommerce子分类页显示父分类名仅展示ID的问题如何解决?

问题根因

原有代码中当检测到当前访问的是子分类时,直接输出了$term->parent字段,该字段存储的是父分类的ID数值而非分类名称,因此只会展示数字ID而不会输出父分类标题。

修复后代码

/*get title*/
function woocommerce_category_title() {
    if ( is_product_category() ){
        $term = get_queried_object();
        if ( $term->parent > 0 ) {
            // 通过父分类ID获取商品分类的完整术语对象
            $parent_term = get_term( $term->parent, 'product_cat' );
            // 异常兼容:父分类不存在时回退显示当前分类名称
            $term_title = !is_wp_error( $parent_term ) ? $parent_term->name : $term->name;
        } else {
            $term_title = $term->name;
        }
        echo $term_title;
    }
}
add_shortcode( 'cattit', 'woocommerce_category_title' );

调整说明

  • 新增get_term()调用,传入父分类ID和商品分类的专属分类法product_cat,拿到父分类的完整数据后取name字段输出
  • 新增异常判断逻辑,避免父分类被误删等异常场景下出现报错
  • 兼容原有父分类页面的展示逻辑,父分类页仍输出当前分类名称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:36:03