Random Free Product For Each Day in WooCommerce

This group of 5 custom functions for WooCommerce enables you to change the price of any product for 24 hrs to free. The code includes a link you can hook in anywhere, by default the header, which display a todays free product message with a link to the single product page.

Once 24 hrs is up, the code chooses another product, changes the price to zero and displays it in the header as the dailly free product while at the same time, returning the previous days product back to it regular price so it’s no longer free.

How The Code Works

The combined functionality in this download is coded to select a random free product each day, set its price to zero, display its name in the site header ( or any other hook location ), using both the original price with a strike through and new price which is zero.

1. Selecting a Random Free Product Each Day :

  • The code uses the get_random_free_product function, which queries your WooCommerce products to find a random product. This is done using the WP_Query class.
  • The assign_random_free_product function runs on the init action hook and checks if today’s date is different from the date stored in the random_free_product_date option. If they are different, it selects a new random free product and updates the random_free_product_id and random_free_product_date options to ensure a fresh selection daily.

2. Displaying the Random Free Product Name in the Header :

  • The display_random_free_product_name function checks if a random product is assigned (via the random_free_product_id option ) and, if so, retrieves its name and product permalink.
  • It displays the product name as a link in the site header, with “Today’s Free Product” added before it. Optionally, it can also display both the original and sale prices with styling on the single product page.

3. Changing the Price to Zero for the Random Free Product :

  • To change the price of the random free product to zero everywhere, including the single product page, cart, and checkout, the change_random_free_product_price function hooks into the woocommerce_product_get_price filter. This function checks if the product is the random free product and sets the price to zero accordingly. This code ensures that the price is consistently displayed as zero in various parts of your WooCommerce site.

Installation

1. Copy all 5 code snippets to the end of your child themes functions file or custom functionality plugin.

2. Copy and paste the CSS to the end of your child themes functions file.

Scheduled Times

Instead of using the assign_random_free_product function, you can create a new function to select a random product and update it hourly, daily, or twice daily using the wp_schedule_event function.

Download Folder

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.