Today let’s look at a simple snippet that hopefully will help someone:)
Task: The client wanted to add badges to some products, depending on the season. First I created four new categories (winter, spring, summer, autumn) and then added the code to functions.php.
//Seasonal badges
add_action( 'woocommerce_before_shop_loop_item_title', 'osw_display_season_badge_woocommerce' );
function osw_display_season_badge_woocommerce() {
global $product;
// Get the list of product categories
$product_categories = wp_get_post_terms( $product->get_id(), 'product_cat', array( 'fields' => 'slugs' ) );
// Check if product belongs to "spring" category
if ( in_array( 'spring', $product_categories ) ) {
// If yes, display "Spring" badge
echo '<span class="spring-badge">Spring 🌸</span>';
} elseif ( in_array( 'winter', $product_categories ) ) {
// If not, check if it belongs to "winter" category
echo '<span class="winter-badge">Winter ⛄</span>';
} elseif ( in_array( 'summer', $product_categories ) ) {
// If not, check if it belongs to "summer" category
echo '<span class="summer-badge">Summer 🌺</span>';
} elseif ( in_array( 'autumn', $product_categories ) ) {
// If not, check if it belongs to "autumn" category
echo '<span class="autumn-badge">Autumn 🍁</span>';
}
}
And styling:
/*seasonal badges*/
.winter-badge, .spring-badge, .autumn-badge, .summer-badge {
padding: 3px 4px;
text-align: center;
background: #FFFFFF;
font-weight: bold;
position: absolute;
top: 6px;
right: 6px;
font-size: 13px;
text-transform: uppercase;
border-radius: 2px;
}
Leave a Reply