Product Badges From Product Tags
Turns chosen product tags into coloured badges on product images, so tagging a product "vegan" or "limited" instantly shows a matching label.
Opens WPIDE on
Code
$wpide_tag_badges = array( // Tag slug => array( label, background colour ).
'vegan' => array( 'Vegan', '#15803d' ),
'limited' => array( 'Limited edition', '#9a3412' ),
'eco' => array( 'Eco friendly', '#0f766e' ),
);
$wpide_tag_badges_html = function () use ( $wpide_tag_badges ) {
global $product;
if ( ! $product instanceof WC_Product ) {
return;
}
$slugs = wp_list_pluck( get_the_terms( $product->get_id(), 'product_tag' ) ?: array(), 'slug' );
$html = '';
foreach ( $wpide_tag_badges as $slug => $badge ) {
if ( in_array( $slug, $slugs, true ) ) {
$html .= sprintf( '<span class="wpide-tag-badge" style="background:%s">%s</span>', esc_attr( $badge[1] ), esc_html( $badge[0] ) );
}
}
if ( $html ) {
echo '<div class="wpide-tag-badges">' . $html . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput -- Escaped above.
}
};
add_action( 'woocommerce_before_shop_loop_item_title', $wpide_tag_badges_html, 9 );
add_action( 'woocommerce_before_single_product_summary', $wpide_tag_badges_html, 9 );
add_action( 'wp_head', function () {
if ( is_woocommerce() ) {
echo '<style>.woocommerce ul.products li.product,.woocommerce div.product{position:relative}.wpide-tag-badges{position:absolute;top:.5em;left:.5em;z-index:9;display:flex;flex-wrap:wrap;gap:4px}.wpide-tag-badge{padding:.2em .55em;border-radius:3px;color:#fff;font-size:.75em;font-weight:600;line-height:1.4}</style>';
}
} );
Notes
Map each tag slug to a label and colour; products with several mapped tags show several badges.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.