Hossein
Hossein

Reputation: 11

how to automatically delete order in wordpress

I wanted to know how to automatically delete an order when a user ordering a Specific product/category if it was in pending in 5m. I have this code but when I add it to my function.php it doesn't work.

function update_order_status( $order_id ) {

    $order        = new WC_Order( $order_id );
    $order_status = $order->get_status();

    if ('pending' == $order_status ) { 
        $current_time = date('h:i:s');    
        sleep(600);  
        wp_delete_post($order_id,true);    
   }

}

Upvotes: 0

Views: 714

Answers (1)

Bhautik
Bhautik

Reputation: 11282

You can use the CRON job and then get all orders with pending status and then check their order date with the current date and delete.

Add custom 5-minute cron schedules by using WC cron_schedules hook

function add_five_minute_cron_schedules($schedules){

    if( !isset( $schedules["five_minute"] ) ){
        $schedules["five_minute"] = array(
            'interval' => 5*60,
            'display'  => __('Once every 5 minutes')
        );
    }

    return $schedules;
}
add_filter('cron_schedules','add_five_minute_cron_schedules');

Scheduled your CRON on WP init Hook.

if( ! wp_next_scheduled( 'remove_pending_order_after_five_minute' ) ){
    wp_schedule_event( time(), 'five_minute', 'remove_pending_order_after_five_minute' );
}
    
//Hook into that action that'll fire every 5 minutes.
add_action( 'remove_pending_order_after_five_minute', 'remove_pending_order_after_five_minute_callback' );

function remove_pending_order_after_five_minute_callback(){

    // get all pending orders that created in the last 5 minutes.
    $args = array(
        'post_status'    => array( 'wc-processing', 'wc-pending', 'wc-on-hold' ),
        'date_created'   => '<' . ( time() - 300 ),
        'posts_per_page' => -1
    );
    
    $orders = wc_get_orders($args);

    if( !empty( $orders ) ){

        // Loop through each $order objects.
        foreach( $orders as $order ){
            
            $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;

            $order = wc_get_order( $order_id );

            if ( $order && sizeof( $order->get_items() ) > 0 ) {    

                foreach( $order->get_items() as $item ) {

                    if( has_term( 'charkh', 'product_cat', $item->get_product_id() ) ) {

                        wp_delete_post( $order_id );      
                        break;  
                        
                    }

                }

            }

        }   

    }

}

This code goes to active theme functions.php file. Tested and works.

Upvotes: 1

Related Questions