-
-
Save spasicm/1a33a5d53e193f06354b9c838036f69b to your computer and use it in GitHub Desktop.
<?php | |
/** 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' ); |
Ah yes that would make sense thank you. Anything else you can think of that I should check since they are still in trash. Website gets many visitors a day as its a large ecommerce website.
Thank you
You are right, I have investigated how the wp_delete_post method works https://developer.wordpress.org/reference/functions/wp_delete_post/
"wp_delete_post() automatically reverts to wp_trash_post() if $force_delete is false, the post_type of $postid is page or post, $postid is not already in the trash and if that trash feature enabled (which it it is by default)."
This means, if the coupons are not already in the trash, they will always be moved to the trash first.
So, if you want to delete the coupons from the trash as well, you need to write a method that will permanently delete the coupons and which will be executed after this method that moves the coupons to the trash.
That's the only way.
Coupons are trashed, but you can comment out first line and uncomment second line if you want to delete expired coupons: