How to automatically delete old completed orders in woocommerce?

Member

by rollin , in category: PHP CMS , 7 months ago

How to automatically delete old completed orders in woocommerce?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 7 months ago

@rollin 

To automatically delete old completed orders in WooCommerce, you can use a plugin called "Auto Delete Order for WooCommerce" or you can add some custom code to your site. Here's how you can achieve this using custom code:

  1. Go to your WordPress admin panel and navigate to Appearance > Theme Editor.
  2. Open the functions.php file of your theme.
  3. Add the following code snippet at the end of the functions.php file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function auto_delete_completed_orders() {
    global $wpdb;
    
    // Set the number of days after which the orders will be deleted
    $days = 30; 
    
    // Get the current date
    $current_date = current_time( 'mysql' );
    
    // Calculate the date to delete orders before
    $delete_date = date( 'Y-m-d H:i:s', strtotime( '-' . $days . ' days', strtotime( $current_date ) ) );
    
    // Delete completed orders older than $days days
    $wpdb->query( 
        "DELETE FROM {$wpdb->posts} WHERE post_type = 'shop_order' 
        AND post_status = 'wc-completed' 
        AND post_date < '{$delete_date}'"
    );
}

// Hook the function to a scheduled event
add_action( 'wp', 'schedule_auto_delete_completed_orders' );
function schedule_auto_delete_completed_orders() {
    if ( !wp_next_scheduled( 'auto_delete_completed_orders' ) ) {
        wp_schedule_event( strtotime( 'midnight' ), 'daily', 'auto_delete_completed_orders' );
    }
}


  1. Save the changes and close the file editor.


This code will schedule a daily event that will run the auto_delete_completed_orders function, which will delete completed orders that are older than a specified number of days. You can adjust the $days variable to change the number of days before orders are deleted.


Please note that modifying the functions.php file directly can be risky if not done correctly. It's always recommended to have a backup of your site before making any changes to your theme files. If you are not comfortable with coding, consider using a plugin or seeking help from a developer.