Coupons are amazing, who does not like a discount? A very common way to give coupons to customers is to create one automatically after their first order, or something like that.

The issue with that though is that usually these coupons expire after a specific period, and by default, WooCommerce will not delete them. They have no reason to stay in your database though, so how do we delete expired coupons automatically?

With a snippet of course.

Open your functions.php file in wp-content/themes/your-child-theme-name/ and add this code at the end of the file:

/**
* Schedule the daily event if necessary.
*/
function schedule_delete_expired_coupons() {
if ( ! wp_next_scheduled( 'delete_expired_coupons' ) ) {
wp_schedule_event( time(), 'daily', 'delete_expired_coupons' );
}
}
add_action( 'init', 'schedule_delete_expired_coupons' );
/**
* Trash all expired coupons when the event is triggered.
*/
function delete_expired_coupons() {
$args = array(
'posts_per_page' => -1,
'post_type' => 'shop_coupon',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'expiry_date',
'value' => current_time( 'Y-m-d' ),
'compare' => '<='
),
array(
'key' => 'expiry_date',
'value' => '',
'compare' => '!='
)
)
);
$coupons = get_posts( $args );
if ( ! empty( $coupons ) ) {
$current_time = current_time( 'timestamp' );
foreach ( $coupons as $coupon ) {
wp_trash_post( $coupon->ID );
}
}
}
add_action( 'delete_expired_coupons', 'delete_expired_coupons' );
view raw functions.php hosted with ❤ by GitHub

This snippet will automatically move to the Trash all the expired coupons in your store so you can go and delete them permanently with one click.

If you want to permanently delete the coupons directly instead of trashing them, you can change this code:

wp_trash_post( $coupon->ID );

to this:

wp_delete_post( $coupon->ID, true );

but beware that once you permanently delete a coupon it cannot be recovered.

Note that it works on WordPress cron jobs. If you disabled them or for any reason, they are not working, this snippet will not work as well.

5 replies
  1. Oliver Koenig
    Oliver Koenig says:

    Hi there. I have the same issue here, the snippet should not delete expired by date coupons but already used coupons. Any ideas in that?
    Thank you so much in advance!

    Reply
  2. Marc
    Marc says:

    This snipped haven’t worked for me. I have added it as Snipppet (executed once) but without effect. Still having over 40’000 coupons in the system (the most of them are expired).

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply