Automating WooCommerce: How to Auto-Draft Expired Event Products with a WordPress Cron Job
To automatically mark products as “draft” when the event date stored in the date
post meta has passed, you can create a scheduled task (cron job) that runs regularly and checks if the event date has passed. If the date has passed, the product will be marked as a draft.
Contents
show
Here’s a step-by-step solution:
Step 1: Add a Custom Cron Job
You can set up a custom cron job that runs daily to check and update the product status based on the date
meta value.
Add the Cron Job to functions.php
:
// Schedule a daily cron job
function schedule_product_status_check() {
if (!wp_next_scheduled('check_product_event_dates')) {
wp_schedule_event(time(), 'daily', 'check_product_event_dates');
}
}
add_action('wp', 'schedule_product_status_check');
// Unschedule the event when the theme is deactivated
function unschedule_product_status_check() {
$timestamp = wp_next_scheduled('check_product_event_dates');
wp_unschedule_event($timestamp, 'check_product_event_dates');
}
add_action('switch_theme', 'unschedule_product_status_check');
This code schedules a daily event called check_product_event_dates
, which will run once a day. The unschedule_product_status_check
function will ensure the event is unscheduled if the theme is deactivated.
Step 2: Create the Function to Update Products Based on the Event Date
Add the Function to Check Dates and Mark Products as Draft:
// Hook the function to the cron event
add_action('check_product_event_dates', 'check_and_update_product_status');
function check_and_update_product_status() {
// Today's date (no time, for comparison)
$today = strtotime(date('Y-m-d'));
// Query WooCommerce products with the 'date' meta key
$args = array(
'post_type' => 'product',
'posts_per_page' => -1, // Get all products
'meta_key' => 'date', // Meta key where event date is stored
'meta_value' => '', // This is required to ensure meta_key is returned
'meta_compare' => 'EXISTS', // Only get products with 'date' meta
);
$products = new WP_Query($args);
if ($products->have_posts()) {
while ($products->have_posts()) {
$products->the_post();
$product_id = get_the_ID();
// Get the event date from the product meta (stored as d.m.Y)
$event_date = get_post_meta($product_id, 'date', true);
// Convert the event date to a timestamp
$event_timestamp = strtotime($event_date);
// Check if the event date has passed
if ($event_timestamp < $today) {
// Update the product status to 'draft' if the event date has passed
$product_data = array(
'ID' => $product_id,
'post_status' => 'draft',
);
wp_update_post($product_data);
// Optionally, add a log or notification
error_log("Product ID {$product_id} marked as draft because the event date has passed.");
}
}
}
// Reset post data
wp_reset_postdata();
}
Explanation:
- Schedule Cron Job:
- The function
schedule_product_status_check()
creates a daily scheduled task that runs the functioncheck_and_update_product_status
once per day.
- The function
- Check Product Event Dates:
check_and_update_product_status()
queries all WooCommerce products that have thedate
meta field.- For each product, it retrieves the
date
meta value (ind.m.Y
format), converts it to a timestamp usingstrtotime()
, and compares it to today’s date. - If the event date has passed, it updates the product status to
draft
usingwp_update_post()
.
- Post Status Update:
- The function
wp_update_post()
is used to mark the product asdraft
if the event date has passed.
- The function
- Logging (Optional):
- The
error_log()
function is used to log the changes. You can use this for debugging or tracking when products are marked as draft.
- The
Step 3: Testing and Customization
- You can manually trigger the function
check_and_update_product_status()
by adding it temporarily to an admin action or by using WP-CLI if you want to test it. - The cron job runs daily (
'daily'
interval). If you want to check more or less frequently, you can adjust the interval by changing'daily'
to'hourly'
,'twicedaily'
, or create a custom interval.
Important Notes:
- Backup Your Data: Since this will affect product status, ensure you have a backup of your site before testing it in a production environment.
- Cron Job Reliability: WordPress cron jobs rely on visitors to your site to trigger the scheduled events. If your site has low traffic, cron jobs might not run exactly on time. You may consider using a real server cron job to ensure timely execution.
Comments
Leave a Comment