WooCommerce产品循环标题上方添加自定义分类法名称失败问题求助
问题排查与修复方案
看起来你离解决问题只差几步啦!我帮你排查了代码里的几个小问题,咱们一个个来修正:
1. get_the_terms 参数使用错误
get_the_terms() 函数并不支持第三个 fields 参数,你想获取术语名称的需求,应该改用 wp_get_post_terms()(它支持 fields 选项),或者在获取到术语对象后手动提取名称。
2. 产品ID获取方式的兼容性问题
WooCommerce 3.0 版本之后,官方推荐使用 $product->get_id() 方法来获取产品ID,直接访问 $product->id 可能在新版本中出现兼容性问题。
3. 术语对象的访问错误
get_the_terms() 返回的是 WP_Term 对象数组,你直接循环输出 $current 会打印整个对象,而不是术语名称,需要改为访问对象的 name 属性。
4. URL判断不够可靠
检查URL的方式容易受 permalink 设置、多语言插件等因素影响,判断产品分类页面最好用 WooCommerce 官方的条件标签 is_product_category('rode-wijn'),更稳定可靠。
修正后的完整代码
add_action( 'woocommerce_before_shop_loop_item_title', 'add_meta_above_title', 10); function add_meta_above_title() { global $product; // 确保产品对象存在,避免报错 if ( ! $product ) return; // 获取产品ID(兼容WooCommerce新版本) $product_id = $product->get_id(); // 获取元数据和分类术语 $winetype = get_post_meta( $product_id, 'wine_type', true ); // 方式1:用wp_get_post_terms直接获取名称数组,更简便 $country_terms = wp_get_post_terms( $product_id, 'country', array( 'fields' => 'names' ) ); // 方式2:如果习惯用get_the_terms,后续需要提取name属性 // $country_terms = get_the_terms( $product_id, 'country' ); // 首页、商店页、产品页显示wine_type元数据 if ( is_front_page() || is_shop() || is_product() ) { if ( ! empty( $winetype ) ) { echo '<div class="product-meta-above-title">' . ucwords( $winetype ) . '</div>'; } } // URL包含/winery/时显示wine_type元数据 if ( strpos( $_SERVER['REQUEST_URI'], "/winery/" ) !== false ) { if ( ! empty( $winetype ) ) { echo '<div class="product-meta-above-title">' . ucwords( $winetype ) . '</div>'; } } // 红葡萄酒分类页显示country分类术语 if ( is_product_category( 'rode-wijn' ) ) { if ( ! empty( $country_terms ) && ! is_wp_error( $country_terms ) ) { // 如果用方式1(直接获取名称数组) foreach ( $country_terms as $country_name ) { echo '<div class="product-meta-above-title">' . ucwords( $country_name ) . '</div>'; } // 如果用方式2(对象数组),切换成这段代码即可 // foreach ( $country_terms as $term ) { // echo '<div class="product-meta-above-title">' . ucwords( $term->name ) . '</div>'; // } } } }
额外测试建议
- 确认目标产品确实已经关联了
country分类的术语(去后台产品编辑页检查分类设置) - 清除网站缓存后刷新红葡萄酒分类页面,查看效果
内容的提问来源于stack exchange,提问作者Casper
相关产品推荐
相关产品推荐

