John Davidson

php - how to automatically delete order in wordpress

0 comments
Message:


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);
}

}


My Answer:
To automatically delete an order in WordPress after 5 minutes if it is in pending status, you can use the following code in your functions.php file:

php
function update_order_status( $order_id ) {
$order = wc_get_order( $order_id );
$order_status = $order->get_status();

if ( 'pending' == $order_status ) {
$current_time = current_time( 'timestamp' );
$order_date = strtotime( $order->get_date_created() );
$difference = $current_time - $order_date;

if ( $difference >= 300 ) { // 300 seconds = 5 minutes
$order->update_status( 'cancelled' );
}
}
}
add_action( 'woocommerce_order_status_pending', 'update_order_status' );


This code will check if the order status is pending and if the order has been pending for more than 5 minutes, it will automatically update the order status to cancelled. This will effectively "delete" the order as it will no longer be visible in the WooCommerce orders list.

Make sure to test this code thoroughly on a staging site before implementing it on a live site to ensure it works as expected.

Rate this post

3 of 5 based on 9030 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us