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_datepicker
Function:- Enqueues the jQuery UI datepicker script.
- Enqueues the jQuery UI datepicker style from the official jQuery CDN.
add_action
Hook:- Hooks the
enqueue_datepicker
function to thewp_enqueue_scripts
action.
- 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_pages
Function:- 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 adiv
with the classcountdown-timer
and adata-expiration
attribute containing the expiration date.
add_action
Hooks:- Hooks the
add_countdown_timer_to_pages
function to thewoocommerce_before_shop_loop_item_title
andwoocommerce_product_thumbnails
actions.
- Hooks the
3. Countdown Timer JavaScript
This JavaScript code initializes the countdown timer for elements with the class countdown-timer
.
startCountdown
Function:- Defines the countdown logic. This function is incomplete in the provided code.
jQuery(document).ready
Function:- Ensures that the code inside runs when the document is ready.
- Initializes a countdown for each element with the class
countdown-timer
. - Calls the
startCountdown
function for each element, passing the element itself and the expiration date from thedata-expiration
attribute.
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-expiration
attribute and calling a function (startCountdown
) to handle the countdown logic.
Was This Tutorial Helpful?