I’m trying to run the following function daily, to auto-complete all processing order older than 10 days and who have a specific custom meta value.
I’m using the following snippet, however this will simply not work. Any idea as to why?
function autoComplete(){
$orders = wc_get_orders( array(
'status' => 'wc-processing',
'date_created' => '<' . ( time() - 10 * DAY_IN_SECONDS ),
'meta_key' => 'status_us',
'meta_compare' => '=',
'meta_value' => 'Sent to USA',
) );
foreach ($orders as $order){
$order->update_status( 'completed' );
}
}
if ( ! wp_next_scheduled( 'autoComplete' ) ) {
wp_schedule_event( time(), 'daily', 'autoComplete' );
}
Is there any error I’ve missed? Thanks for your help!
2
Answers
Here is what I do to validate orders based on a CRON task.
I believe that you don’t need the "wc-" prefix.
Are you sure that your scheduled event is working? and that
$orders
is filled? Please test your method without the schedule first.You did a good attempt but you made a few mistakes.
The following code goes inside your
functions.php
.Your function has minor errors
bks_mark_processing_order_complete_if_sent_to_usa()
Mistake Explanations
While your attempt was in right direction but
'date_created' => '<' . ( time() - 10 * DAY_IN_SECONDS ),
you had to use>
instead of<
also you didn’t acutally setDAY_IN_SECONDS
You had to replace it with 86400. So the correct value would be'>' . ( time() - 864000 )
. For 10 days10 * 86400 = 864000
. You can read about this explanation here in the WooCommerce documentation.Here I have created new custom variable for you which is set using
woocommerce_order_data_store_cpt_get_orders_query
and then queried. Code that needs to be added.$order->save();
So to summarise you have to add the following code in your functions.php
The above code is TESTED and WORKS.
Proof:
Install WP CRON plugin to check your cron. See above screenshot. You can test by hitting
Run Now
.