Are you tired of the same old “Sale!” badge on your WooCommerce products? Want to create a more engaging and dynamic shopping experience for your customers?
In this blog post, we’ll guide you through a simple PHP/JS customization that replaces the static “Sale!” badge on the WooCommerce Single Product page with a captivating countdown timer. This will not only add excitement to your product page but also encourage customers to make a purchase before the sale ends.
Get ready to elevate your WooCommerce store and boost your sales with this effective customization. Enjoy!
PHP (+JS) Snippet: Turn “Sale!” Badge Into A Countdown Timer @ WooCommerce Single Product Page
Of course, this will only work on the single product page AND if you have specified a “sale end date”, because the script needs to calculate the remaining time between now and the future sale end date.
/**
* @snippet Sale End Date Countdown Timer
* @how-to businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @testedwith WooCommerce 9
* @community https://businessbloomer.com/club/
*/
add_filter( 'woocommerce_sale_flash', 'bbloomer_sale_end_date', 9999, 3 );
function bbloomer_sale_end_date( $html, $post, $product ) {
if ( is_product() && $product->get_date_on_sale_to() ) {
$now = time();
$sale_price_dates_to_timestamp = $product->get_date_on_sale_to()->getTimestamp();
$datediff = $sale_price_dates_to_timestamp - $now;
$days = floor( $datediff / 86400 );
$hours = floor( ( $datediff - $days * 86400 ) / 3600 );
$mins = floor( ( $datediff - $days * 86400 - $hours * 3600 ) / 60 );
$secs = floor( ( $datediff - $days * 86400 - $hours * 3600 - $mins * 60 ) / 60 );
wc_enqueue_js( "
var end = new Date( " . $sale_price_dates_to_timestamp * 1000 . " );
setInterval( function() { bbcountdown( end ); }, 1000 );
function bbcountdown( endTime ) {
var now = Date.now();
var timeLeft = ( endTime - now ) / 1000;
var days = Math.floor( timeLeft / 86400 );
var hours = Math.floor( ( timeLeft - ( days * 86400 ) ) / 3600 );
var mins = Math.floor( ( timeLeft - ( days * 86400 ) - ( hours * 3600 ) ) / 60 );
var secs = Math.floor( ( timeLeft - ( days * 86400 ) - ( hours * 3600 ) - ( mins * 60 ) ) );
$('.countdown .days').text( days );
$('.countdown .hours').text( hours );
$('.countdown .mins').text( mins );
$('.countdown .secs').text( secs );
}
" );
return '<span class="onsale countdown">Sale ends in <span class="days">' . $days . '</span>d <span class="hours">' . $hours . '</span>h <span class="mins">' . $mins . '</span>m <span class="secs">' . $secs . '</span>s</span>';
}
return $html;
}