Search code examples
phpwordpresswoocommercecronorders

Update order status from processing to completed in WooCommerce automatically on every Monday


I need to update the order status of all 'processing' orders after a specific period of time in WooCommerce. I aimed to do this via cron job. So I added this hook in WP Control, with a weekly schedule: woocommerce_complete_processing_order_weekly

Here is what I added in my functions.php:

add_action( 'woocommerce_complete_processing_order_weekly', 'custom_woocommerce_complete_order', 10, 0 );

function custom_woocommerce_complete_order ( $order_id ) { 
    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );
    $order->update_status( 'completed' );
}

Could you help me out with this?


Solution

  • add_action( 'admin_init', 'update_order_status_on_monday' );
    
    function update_order_status_on_monday() {
    
        if ( date( 'D', strtotime( 'now' ) ) === 'Mon' && !get_transient( '_updated_order_status_on_monday' ) ) {
    
            $processing_orders   = wc_get_orders( $args              = array(
                'numberposts'    => -1,
                'post_status'    => 'wc-processing',
            ) );
    
            if ( !empty( $processing_orders ) ) {
                foreach ( $processing_orders as $order )
                    $order->update_status( 'completed' );
            }
            set_transient( '_updated_order_status_on_monday', true );
        } elseif ( date( 'D', strtotime( 'now' ) ) !== 'Mon' ) {
            delete_transient( '_updated_order_status_on_monday' );
        }
     }
    

    Add this code into your active theme functions.php