WooCommerce商品分类样式定制及多分类展示问题求助
WooCommerce商品分类展示与背景色定制代码方案
代码实现
add_action( 'woocommerce_before_shop_loop_item_title', 'custom_product_category_display', 10 ); add_action( 'woocommerce_single_product_summary', 'custom_product_category_display', 5 ); function custom_product_category_display() { global $product; if ( ! $product ) return; // 获取商品所属所有产品分类 $categories = get_the_terms( $product->get_id(), 'product_cat' ); if ( empty( $categories ) ) return; // 初始化三类分类变量 $product_line = ''; $body_part = ''; $usage_type = ''; // 遍历分类,按类型归类 foreach ( $categories as $category ) { // 替换为你实际的分类slug或名称判断逻辑 switch( $category->slug ) { // 产品线分类slug示例 case 'super-line': case 'premium-line': case 'basic-line': $product_line = $category->name; break; // 身体部位分类slug示例 case 'body': case 'head': $body_part = $category->name; break; // 家用/商用分类slug示例 case 'home-use': case 'commercial-use': $usage_type = $category->name; break; } } // 拼接前两类分类文本 $display_text = ''; if ( $product_line && $body_part ) { $display_text = $product_line . ' | ' . $body_part; } elseif ( $product_line ) { $display_text = $product_line; } elseif ( $body_part ) { $display_text = $body_part; } // 构建输出内容 $output = ''; if ( $display_text ) { // 根据产品线添加对应背景色类 $bg_class = ''; switch( $product_line ) { case 'SUPER LINE': $bg_class = 'bg-super-line'; break; case 'PREMIUM LINE': $bg_class = 'bg-premium-line'; break; case 'BASIC LINE': $bg_class = 'bg-basic-line'; break; // 更多产品线可继续添加 } $output .= '<div class="product-category-badge ' . esc_attr( $bg_class ) . '">' . esc_html( $display_text ) . '</div>'; } // 添加家用/商用分类标注 if ( $usage_type ) { $output .= '<div class="product-usage-badge">' . esc_html( $usage_type ) . '</div>'; } echo $output; }
配套CSS样式(添加到主题自定义CSS或style.css)
/* 产品线分类徽章基础样式 */ .product-category-badge { display: inline-block; padding: 4px 8px; border-radius: 4px; color: #fff; font-size: 12px; margin-bottom: 8px; } /* 不同产品线背景色定制 */ .bg-super-line { background-color: #ff4444; /* 可自行修改颜色值 */ } .bg-premium-line { background-color: #00C851; } .bg-basic-line { background-color: #33b5e5; } /* 家用/商用标注样式 */ .product-usage-badge { display: inline-block; padding: 2px 6px; border: 1px solid #ccc; border-radius: 4px; font-size: 11px; margin-left: 8px; } /* 单个商品页面适配 */ .single-product .product-category-badge { margin-top: 8px; }
关键说明
- 分类匹配逻辑:代码中通过分类
slug判断分类类型,你需要将示例中的slug替换成你店铺实际的分类slug(可在WooCommerce分类编辑页查看) - 背景色扩展:如果有更多产品线,只需在PHP的
switch语句和CSS中添加对应类和颜色即可 - 页面适配:代码同时挂载了店铺列表页和商品详情页的钩子,确保两个页面都能显示自定义分类信息
内容的提问来源于stack exchange,提问作者Rick131
相关产品推荐
相关产品推荐

