So with the help of the LoicTheAztec over at StackOverflow, I’ve been able to get this to work with products bulk uploaded via csv product import.
I’ve customized the function slightly from the answer in the StackOverflow post for my specific needs, here’s the code I’m using for anyone who might have the same issue I was having:
// Custom Cron hooked Function called by wp_schedule_event
add_action( 'jape_pre_order_stock_update', 'update_pre_order_stock_status' );
function update_pre_order_stock_status(){
// Get all related product IDs to update via a WP_Query
$products_ids = get_posts( [
'post_type' => 'product',
'post_status' => 'publish',
'numberposts' => 100, // <= the number of products to process (-1 is all)
'fields' => 'ids',
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array(
'comic-book-pre-orders',
'dc-comics-pre-orders',
'image-comics-pre-orders',
'manga-pre-orders',
'marvel-comics-pre-orders',
'other-publisher-pre-orders',
),
) ),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '=',
),
array(
'key' => 'woo_expiry_date',
'value' => date_i18n('Y-m-d'),
'compare' => '<=',
'type' => 'DATE',
),
array(
'key' => 'woo_expiry_action',
'value' => 'out',
'compare' => '=',
),
),
] );
foreach( $products_ids as $product_id ) {
$product = wc_get_product($product_id);
$product->set_stock_quantity(0); // Set stock quantity
$product->set_stock_status('outofstock'); // Set stock status
$product->save(); // Save updated product data
}
rocket_clean_post( $product );
}
// Cron schedule event function
function cron_starter_daily_products_update() {
if ( ! wp_next_scheduled( 'jape_pre_order_stock_update' ) ) {
wp_schedule_event( strtotime( 'midnight' ), 'daily', 'jape_pre_order_stock_update' );
}
}
cron_starter_daily_products_update(); // Initiate cron schedule event
So this runs a cron job that will search for products in a set array of product categories that are in stock and have ‘woo_expiry_date’ metadata set to a date equal to or earlier than the current date, and ‘woo_expiry_action’ set to ‘out’.
When it finds these products it updates the stock quantity to ‘0’, the stock status to ‘outofstock’, and saves them.
I use WP Rocket to cache my site and found that though the function worked as I wanted, the cache needed to be flushed for the change to be viewable on the frontend for non-admin users.
To resolve this I added rocket_clean_post( $product );
which flushes the cache of the updated products only.
If you’re not using WP Rocket this won’t be needed, though you may need something similar if you’re using another cache plugin.
-
This reply was modified 9 months, 3 weeks ago by
JapeNZ.
-
This reply was modified 9 months, 3 weeks ago by
JapeNZ.