skip to Main Content

I need to change the status of my orders to (Cancelled) automatically after 7 days if it is not processed.

I need to change the status from: New Request to Cancelled.
Or
I need to change the status from: Processing to Cancelled.

Thanks
Adnan

2

Answers


  1. Chosen as BEST ANSWER

    I did that with the help of this code:

    function autocancel_wc_orders(){
        $query = ( array(
            'limit'   => 10,
            'orderby' => 'date',
            'order'   => 'DESC',
            'status'  => array( 'wc-pending', 'wc-ywraq-new', 'wc-ywraq- 
            pending')
        ) );
        $orders = wc_get_orders( $query );
        foreach( $orders as $order ){       
    
            $date     = new DateTime( $order->get_date_created() );
            $today    = new DateTime();
            $interval = $date->diff($today);
    
            $datediff = $interval->format('%a');
    
            if( $datediff > 2 ){
                $order->update_status('cancelled', 'Cancelled for missing 
                payment');
            }   
        }
    } 
    add_action( 'admin_init', 'autocancel_wc_orders' );
    

    I found this answer online in the link: https://samuelsilva.pt/cancel-woocommerce-not-paid-orders-automatically/


  2. Helpful documentation – https://developer.wordpress.org/reference/classes/wp_query/#date-parameters
    https://woocommerce.wp-a2z.org/oik_api/wc_get_order_statuses/

    //My server cronjob is targeting wp-cron.php 
    function ss_cancel_failed_orders() {
        $held_duration = 15; //minutes how often my cron job to run per day/hour
        $data_store = WC_Data_Store::load('order');
    
        //Change post_status for desired order statuses
        //Change date_query before value to desired time compare with modified post date
        $unpaid_orders = get_posts(array('posts_per_page' => -1, 'post_type' => 'shop_order', 'post_status' => array('wc-failed','wc-on-hold'), 'date_query' => array(array('before' => '15 minutes ago', 'column'=>'post_modified' ))));
        if ( $unpaid_orders ) {
            foreach ( $unpaid_orders as $unpaid_order ) {
                $order = wc_get_order( $unpaid_order );
                $order->update_status( 'cancelled', __( 'Order has expired.', 'woocommerce' ) ); // Status here is without wc- prefix
            }
        }
        wp_clear_scheduled_hook( 'ssa_cancel_failed_orders' );
        wp_schedule_single_event( time() + ( absint( $held_duration ) * 60 ), 'ssa_cancel_failed_orders' ); // you can remove wp cron and work with server cron only
      }
      add_action('ssa_cancel_failed_orders', 'ss_cancel_failed_orders');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search