
本文介绍如何在 woocommerce 商品循环(shop loop)中,为每个商品自动显示其所属首个产品分类的自定义缩略图徽章,兼容现代 woocommerce 版本,支持响应式图片属性与占位图回退。
在 WooCommerce 商城中,常需通过视觉化方式快速传达商品归属(如品牌、系列或品类),例如在商品卡片顶部展示“Sunglasses”分类的专属图标徽章。原始代码存在多个问题:错误使用已废弃的 get_woocommerce_term_meta()、未适配新版 WooCommerce 的 WP_Query 上下文($product 对象更可靠)、逻辑混淆(误判 is_product() 导致钩子在目录页失效)、且未处理无缩略图时的降级方案。
以下为优化后的专业实现方案:
✅ 正确钩子与上下文
使用 woocommerce_before_shop_loop_item_title 钩子(优先级 20,避免与其他插件冲突),并在函数内直接调用 $product->get_id() 获取当前商品 ID —— 这比依赖全局 $post 更健壮,尤其在 AJAX 或自定义查询场景下。
✅ 获取首个有效分类并读取缩略图
add_action('woocommerce_before_shop_loop_item_title', 'display_product_category_thumbnail', 20);
function display_product_category_thumbnail() {
global $product;
// 获取商品所属的第一个 product_cat 分类(跳过空值)
$terms = get_the_terms($product->get_id(), 'product_cat');
$productFirstCategory = $terms && ! is_wp_error($terms) ? reset($terms) : null;
if ( ! $productFirstCategory ) {
return;
}
// 定义缩略图尺寸(复用 WooCommerce 内置尺寸)
$small_thumb_size = 'woocommerce_thumbnail';
$dimensions = wc_get_image_size($small_thumb_size);
// 读取分类元数据中的 thumbnail_id(新版推荐用 get_term_meta)
$thumbnail_id = get_term_meta($productFirstCategory->term_id, 'thumbnail_id', true);
if ($thumbnail_id && wp_get_attachment_image_src($thumbnail_id, $small_thumb_size)) {
$image_data = wp_get_attachment_image_src($thumbnail_id, $small_thumb_size);
$image = is_array($image_data) ? $image_data[0] : '';
$srcset = function_exists('wp_get_attachment_image_srcset')
? wp_get_attachment_image_srcset($thumbnail_id, $small_thumb_size)
: '';
$sizes = function_exists('wp_get_attachment_image_sizes')
? wp_get_attachment_image_sizes($thumbnail_id, $small_thumb_size)
: '(max-width: 350px) 100vw, 350px';
} else {
// 回退至 WooCommerce 占位图
$image = wc_placeholder_img_src();
$srcset = $sizes = '';
}
// 输出语义化徽章容器(建议配合 CSS 控制尺寸与定位)
if ($image) {
echo '';
}
}⚠️ 注意事项与最佳实践
- 分类缩略图设置:确保已在 WordPress 后台 → 产品 → 分类中,为对应分类上传并保存「分类图像」(该操作会自动写入 thumbnail_id 元字段);
- CSS 样式建议:.brand-icon-logo { position: absolute; top: 12px; left: 12px; z-index: 2; } 配合 position: relative 的商品容器;
- 性能优化:已启用 loading="lazy" 和响应式 srcset/sizes,适配移动端;
-
多分类场景说明:本方案默认取首个分类(最常用场景);若需匹配特定父分类(如仅显示 sunglasses 下的子类),可扩展条件判断,例如:
if ($productFirstCategory->parent === get_term_by('slug', 'sunglasses', 'product_cat')->term_id)
此实现简洁、健壮、可维护,适用于 WooCommerce 6.0+ 及主流主题(如 Storefront、Astra),是展示品类身份标识的专业级解决方案。





