Skip to content

Instantly share code, notes, and snippets.

@eksiscloud
Last active September 4, 2023 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eksiscloud/be60a5833e812372b634b6396adcbb73 to your computer and use it in GitHub Desktop.
Save eksiscloud/be60a5833e812372b634b6396adcbb73 to your computer and use it in GitHub Desktop.
Delete coupons of Woocommerce when those are expired
/**
* add this in the functions.php of theme/child theme/snippets plugin
* 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' );
@eksiscloud
Copy link
Author

If you want to delete expired coupond instead trashing, replace this
wp_trash_post( $coupon->ID );
with this:
wp_delete_post( $coupon->ID, true );

@spasicm
Copy link

spasicm commented Sep 4, 2023

This code is outdated. Its not working because WooCoommerce has changed a way how some data is stored in the database.

I have created GIST with updated solution which is tested and its working ⬇️
gist.github.com/spasicm/1a33a5d53e193f06354b9c838036f69b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment