Display a “New” badge automatically on products published within the last 30 days.
Steps
- Add the code below to your theme’s
functions.php. - Change
30to the number of days you want. - Add CSS to style the badge if required.
Optional CSS
.custom-new-badge {
position: absolute;
top: 10px;
left: 10px;
z-index: 5;
background: #000;
color: #fff;
padding: 5px 10px;
font-size: 12px;
font-weight: 600;
border-radius: 3px;
}
/**
* Add "New" badge to recently published WooCommerce products
*/
function custom_woocommerce_new_product_badge() {
global $product;
if ( ! $product ) {
return;
}
$days = 30;
$created_date = $product->get_date_created();
if ( $created_date && $created_date->getTimestamp() >= strtotime( "-{$days} days" ) ) {
echo '<span class="custom-new-badge">New</span>';
}
}
add_action( 'woocommerce_before_shop_loop_item_title', 'custom_woocommerce_new_product_badge', 5 );