如何在WooCommerce单个商品标题中显示所有关联商品分类?
解决WooCommerce商品显示所有关联分类的问题
原代码未处理分类获取失败的情况,且多分类输出逻辑不规整,导致无法正常展示所有关联分类。以下是两种可行的修改方案:
方案一:用分隔符拼接所有分类
这种方式会把所有分类用指定符号(如逗号)连接,整体输出:
function category_single_product(){ // 获取当前商品的所有商品分类 $terms = get_the_terms( get_the_ID(), 'product_cat' ); // 校验分类是否有效,避免报错 if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) { $category_list = array(); // 遍历收集所有分类名称 foreach ( $terms as $term ) { $category_list[] = $term->name; } // 用逗号拼接并输出,可自行修改分隔符(如`' | '`) echo '<b><span itemprop="name" class="product_category_title">' . implode( ', ', $category_list ) . '</span></b>'; } } add_action( 'woocommerce_before_shop_loop_item_title', 'category_single_product', 25 );
方案二:每个分类单独输出元素
如果需要让每个分类以独立样式展示(比如标签形式),可以用这个版本:
function category_single_product(){ $terms = get_the_terms( get_the_ID(), 'product_cat' ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) { // 遍历逐个输出分类 foreach ( $terms as $term ) { echo '<b><span itemprop="name" class="product_category_title">' . $term->name . '</span></b> '; } } } add_action( 'woocommerce_before_shop_loop_item_title', 'category_single_product', 25 );
你可以通过CSS调整product_category_title类的样式,比如添加左右间距,让分类之间更清晰。
内容的提问来源于stack exchange,提问作者zonic
相关产品推荐
相关产品推荐

