How to Delete expired coupons automatically in Woocommerce

Coupons are a great way to offer discounts and rewards to your customers, and can help promote sales across your shop but problem is that coupons have some expire time. After some specific time, coupons are expire and by default WooCommerce will not delete them. So How to Delete expired coupons automatically in Woocommerce? So here is solution. Let’s have a look.

So here is my code. Just copy this code and paste this code at the end of your theme’s functions.php file of your active child theme (or theme) and Save the file.

Using this code, all expired coupons move to Trash folder, You can see it on Dashboard->WooCommerce->Coupons. so you can delete permanently as you wish.

function wp_schedule_delete_expired_coupons() {
	if ( ! wp_next_scheduled( 'delete_expired_coupons' ) ) {
		wp_schedule_event( time(), 'daily', 'delete_expired_coupons' );
	}
}
add_action( 'init', 'wp_schedule_delete_expired_coupons' );

function wp_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', 'wp_delete_expired_coupons' );

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

wp_trash_post( $coupon->ID );

Replace upper line of code by below line of code.

wp_delete_post( $coupon->ID, true );

So Your expired coupons permanently deleted and it cannot be recovered.

Scroll to Top