Drawing attention to new arrivals in your online store is crucial for engaging customers and boosting sales. One effective method is to add a prominent “New” badge to recently added products. In this tutorial, we’ll demonstrate how to implement this feature on both the product archive and single product pages in your WooCommerce store.
Step 1: Add the Badge with Custom Function
/**
* Snippet Name: Adding New Badge on product archive and single product page
* Snippet Author: wpsnippets.dev
*/
// Add a "New" badge to recently added products in WooCommerce archive
function wps_add_new_badge($args) {
global $product;
$days_old = 5; // Number of days to consider a product as "new"
$product_date = strtotime($product->get_date_created());
$new_threshold = strtotime("-{$days_old} days");
if ($product_date > $new_threshold) {
$args['class'] = 'new-product-badge';
}
return $args;
}
add_filter('woocommerce_post_class', 'wps_add_new_badge');
Step 2: Style the Badge with CSS
/* Style for the "New" badge on WooCommerce product archive */
.new-product-badge {
position: relative;
}
.new-product-badge::after {
content: 'New' !important;
position: absolute;
top: 5px;
left: 5px;
background-color: #ff6347; /* Adjust the background color to your preference */
color: #fff; /* Adjust the text color to your preference */
padding: 3px 6px;
font-size: 12px;
font-weight: bold;
border-radius: 3px;
}
Code Explanation
- This code snippet utilizes the
woocommerce_post_class
filter hook to add anew-product-badge
class to products created within the specified number of days (in this example, 5 days). - The snippet checks the creation date of each product and compares it to the threshold date to determine if it should be marked as “New.”
- The function code goes under the function.php file, and the CSS part goes under the style.css file of your child theme.