Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins

How to Add a Free Product Based on Time & Date Range in WooCommerce?

Whether it’s a flash sale, a weekend special, or a holiday promotion, similar to BOGO offers you can allow time-based free gifts as well. The following code implements the functionality to add free products during the specified time period and also for every multiple of 3 items in the cart.

// Utility function that gives the free product during the discount period
function ts_get_free_product_period() {

    // Set the free product IDs
    $free_product_ids = array(470); // IDs of products eligible for free

    // Set the start time and the end time
    // Parameters: mktime(hour, minute, second, month, day, year)
    $start_time = mktime(11, 00, 00, date("01"), date("01"), date("2024"));
    $end_time   = mktime(3, 00, 00, date("01"), date("20"), date("2024"));
    $time_now   = strtotime("now");

    // Return the array of free product IDs during the allowed period or an empty array outside the period
    return $start_time <= $time_now && $end_time > $time_now ? $free_product_ids : array();

// Enable calculated free products during the discount period
add_filter('woocommerce_cart_calculate_fees', 'ts_periodic_free_products', 99);

function ts_periodic_free_products($cart) {
    $free_product_ids = ts_get_free_product_period();

    // Check if the current cart total quantity is a multiple of 3
    $cart_quantity = WC()->cart->get_cart_contents_count();

    if ($cart_quantity % 3 === 0) {
        foreach ($free_product_ids as $free_product_id) {
            // Display a notice message
            wc_add_notice(__('Free product added to your cart!'), 'success');

            // Add a fee to the cart
            $cart->add_fee(__('Free product fee'), 0, false, 'free_product_' . $free_product_id);

            // Add the free product to the cart

// Handling variation prices caching
add_filter('woocommerce_get_variation_prices_hash', 'ts_add_free_product_to_variation_prices_hash', 99, 1);

function ts_add_free_product_to_variation_prices_hash($hash) {
    if (!empty(ts_get_free_product_period())) {
        $hash[] = 'free_product_variation';
    return $hash;


In the provided output, the free product is added when the current time & date falls within the specified time range in the code, and the product quantity is a multiple of 3. Additionally, a notice message is shown to inform the customer that the free gift has been added.

How to Add a Free Product Based on Time & Date Range in WooCommerce? - Tyche Softwares

Similarly, you can also automatically add a product to your WooCommerce cart based on 6 different conditions covering cart total, categories, on website visit, and many more.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x