Last active
October 4, 2023 15:43
-
-
Save spasicm/1a33a5d53e193f06354b9c838036f69b to your computer and use it in GitHub Desktop.
WooCoommerce Delete Expired Coupons Automatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** WooCommerce automatically delete expired coupons */ | |
// WP Crone adding new interval schedule | |
add_filter( 'cron_schedules', 'cron_add_custom_interval' ); | |
function cron_add_custom_interval( $schedules ) { | |
// Adds custom time interval to the existing schedules | |
$schedules['custominterval'] = array( | |
'interval' => 86400, // in seconds | |
'display' => __( 'Custom interval' ) | |
); | |
return $schedules; | |
} | |
// Schedule coupons delete event | |
function wp_schedule_delete_expired_coupons() { | |
if ( ! wp_next_scheduled( 'delete_expired_coupons' ) ) { | |
wp_schedule_event( time(), 'custominterval', 'delete_expired_coupons' ); | |
// instead of 'custominterval', you can use default values: hourly, twicedaily, daily, weekly | |
} | |
} | |
add_action( 'init', 'wp_schedule_delete_expired_coupons' ); | |
// Find and trash/delete expired coupons | |
function wp_delete_expired_coupons() { | |
$args = array( | |
'posts_per_page' => -1, // -1 is for all coupons, you can enter any other number to limit the number of coupons that will be trashed/deleted per execution | |
'post_type' => 'shop_coupon', | |
'post_status' => 'publish', | |
'meta_query' => array( | |
'relation' => 'AND', | |
array( | |
'key' => 'date_expires', | |
'value' => time(), | |
'compare' => '<=' | |
), | |
array( | |
'key' => 'date_expires', | |
'value' => '', | |
'compare' => '!=' | |
) | |
) | |
); | |
$coupons = get_posts( $args ); | |
if ( ! empty( $coupons ) ) { | |
foreach ( $coupons as $coupon ) { | |
wp_trash_post( $coupon->ID ); // Trash coupons | |
// wp_delete_post( $coupon->ID, true ); // Delete coupons | |
} | |
} | |
} | |
add_action( 'delete_expired_coupons', 'wp_delete_expired_coupons' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment