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

如何在WooCommerce中正确获取自定义分类sale_type的术语?

WooCommerce自定义分类术语无法显示的解决方法

问题分析

你注册了sale_type自定义分类并关联到WooCommerce产品,但前台调用wp_get_post_terms或get_the_terms无法获取到已选中的术语,核心原因有两点:

  1. 自定义分类注册参数不完整,导致术语无法被前台查询到
  2. 未刷新WordPress固定链接规则,分类的重写规则未生效

修正自定义分类注册代码

你的注册代码缺少关键参数,导致分类术语无法被前台正常读取。更新后的代码如下:

function add_custom_taxonomies() {
  register_taxonomy('sale_type', 'product', array(
    'hierarchical' => true,
    // 新增关键参数,确保分类在前台可见且可查询
    'public' => true,
    'query_var' => true,
    'show_in_nav_menus' => true,
    'show_admin_column' => true, // 在产品列表页显示该分类列
    'labels' => array(
      'name' => _x( 'Sale Type', 'taxonomy general name' ),
      'singular_name' => _x( 'Sale Type', 'taxonomy singular name' ),
      'search_items' =>  __( 'Search Sale Type' ),
      'all_items' => __( 'All Sale Type' ),
      'parent_item' => __( 'Parent Sale Type' ),
      'parent_item_colon' => __( 'Parent Sale Type:' ),
      'edit_item' => __( 'Edit Sale Type' ),
      'update_item' => __( 'Update Sale Type' ),
      'add_new_item' => __( 'Add New Sale Type' ),
      'new_item_name' => __( 'New Sale Type Name' ),
      'menu_name' => __( 'Sale Type' ),
    ),
    'rewrite' => array(
      'slug' => 'sale-type',
      'with_front' => false,
      'hierarchical' => true
    ),
  ));
}
add_action( 'init', 'add_custom_taxonomies', 0 );

核心新增参数说明:

  • public => true:确保分类在前台可见,允许通过查询获取术语
  • query_var => true:启用分类的查询变量,让WordPress能识别该分类的查询
  • show_admin_column => true:方便在后台产品列表快速查看产品关联的sale_type

正确获取分类术语的代码(带错误处理)

原代码未做错误判断,若未获取到术语会直接报错。更新后的代码增加了有效性检查:

<span class="badge">
    <?php
    $terms = wp_get_post_terms(get_the_ID(), 'sale_type', array('fields' => 'all'));
    if (!empty($terms) && !is_wp_error($terms)) {
        $term = reset($terms);
        echo esc_html($term->name);
    } else {
        echo '未设置销售类型'; // 可选:默认显示文本
    }
    ?>
</span>

<span class="badge"><?php 
$terms = wp_get_post_terms(get_the_ID(), 'product_cat');
if (!empty($terms) && !is_wp_error($terms)) {
    $term = reset($terms);
    echo esc_html($term->name);
}
?></span>
  • 使用get_the_ID()替代get_the_id()(规范写法)
  • 增加!is_wp_error($terms)检查,避免函数调用出错时抛出警告
  • 用esc_html()转义输出内容,防止XSS安全问题

关键调试步骤

  1. 刷新固定链接规则:进入WordPress后台「设置」→「固定链接」,无需修改任何设置,直接点击「保存更改」,确保自定义分类的重写规则生效。
  2. 重新关联术语:打开产品编辑页,重新选择sale_type术语并更新产品,确保术语关联关系被正确保存。
  3. 明确分类存储逻辑:自定义分类术语不会存在于post meta中,而是存储在wp_term_relationships、wp_terms、wp_term_taxonomy这三张数据表中,所以通过post meta是查不到的,必须用wp_get_post_terms或get_the_terms这类专用函数获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 11:07:27