This downloadable code is a combination of PHP and jQuery used to display a countdown timer on both single products and shop loop archives in WooCommerce. This timer is commonly used in scenarios like product sales where you want to show how much time is left until a special offer ends.

The code adds a date picker on the edit product page enabling you to set a countdown date for each single product. If the date is selected and saved, the countdown timer is displayed inline with the default sales flash. If no date is chosen, the timer does not display.

Installation
There’s 3 simple steps :
1. Copy and paste the PHP code to the end of your child themes functions file or custom functionality/code snippets plugin.
2. Upload the countdown.js file to your child theme folder.
3. Copy and paste the CSS to the end of your child themes style.css file and clear caching.
Code Explanation
Here’s an explanation of each part of the code:
1. Enqueue Scripts in functions.php
This function ensures that the required scripts for jQuery, jQuery UI, and the datepicker are loaded on the front end.
enqueue_datepickerFunction:- Enqueues the jQuery UI datepicker script.
- Enqueues the jQuery UI datepicker style from the official jQuery CDN.
add_actionHook:- Hooks the
enqueue_datepickerfunction to thewp_enqueue_scriptsaction.
- Hooks the
2. Countdown Timer PHP and JavaScript in functions.php
This set of functions manages the display of a countdown timer on WooCommerce shop loop and single product pages.
add_countdown_timer_to_pagesFunction:- Retrieves the current product ID.
- Gets the expiration date from the product meta using
_expiration_date. - Checks if the expiration date is not empty.
- Echoes HTML code containing a span with the class
onsale, the text “Sale Ends:”, and adivwith the classcountdown-timerand adata-expirationattribute containing the expiration date.
add_actionHooks:- Hooks the
add_countdown_timer_to_pagesfunction to thewoocommerce_before_shop_loop_item_titleandwoocommerce_product_thumbnailsactions.
- Hooks the
3. Countdown Timer JavaScript
This JavaScript code initializes the countdown timer for elements with the class countdown-timer.
startCountdownFunction:- Defines the countdown logic. This function is incomplete in the provided code.
jQuery(document).readyFunction:- Ensures that the code inside runs when the document is ready.
- Initializes a countdown for each element with the class
countdown-timer. - Calls the
startCountdownfunction for each element, passing the element itself and the expiration date from thedata-expirationattribute.
Summary:
- The PHP functions handle the server-side logic, fetching the expiration date and outputting HTML with relevant classes and attributes.
- JavaScript is used to initialize the countdown timer on the client side, fetching the expiration date from the
data-expirationattribute and calling a function (startCountdown) to handle the countdown logic.
Related Solutions






Leave a Reply