Skip to content

Instantly share code, notes, and snippets.

@SiR-DanieL
Last active October 30, 2023 10:00
Show Gist options
  • Save SiR-DanieL/e02ca1769c1100de7b908e9ee106a34d to your computer and use it in GitHub Desktop.
Save SiR-DanieL/e02ca1769c1100de7b908e9ee106a34d to your computer and use it in GitHub Desktop.
Delete Expired Coupons Automatically
<?php
// Delete Expired Coupons that have an expiration date set and are not from AutomateWoo
add_action('delete_expired_coupons_hook', 'delete_expired_coupons_action');
function delete_expired_coupons_action() {
$query_args = [
'fields' => 'ids',
'post_type' => 'shop_coupon',
'post_status' => 'any',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'ASC',
'no_found_rows' => true,
'meta_query' => [
[
'key' => 'date_expires',
'value' => '',
'compare' => '!='
],
[
'key' => '_is_aw_coupon',
'value' => false,
],
[
'key' => 'date_expires',
'value' => current_time( 'timestamp' ),
'compare' => '<',
],
],
];
$query = new \WP_Query($query_args);
$coupons = $query->posts;
if (!empty($coupons)) {
foreach ($coupons as $coupon_id) {
wp_trash_post($coupon_id);
}
}
}
// Schedule the Deletion (If Not Already Scheduled)
add_action('init', 'schedule_delete_expired_coupons');
function schedule_delete_expired_coupons() {
if (!wp_next_scheduled('delete_expired_coupons_hook')) {
wp_schedule_event(time(), 'daily', 'delete_expired_coupons_hook');
}
}
// Manual Deletion Button in Marketing > Coupons
add_action('restrict_manage_posts', 'custom_add_delete_expired_button', 99);
function custom_add_delete_expired_button() {
global $typenow;
if ('shop_coupon' === $typenow) {
?>
<form method="post" style="display:inline;">
<input type="hidden" name="custom_action" value="delete_expired_coupons">
<?php wp_nonce_field('custom_delete_expired_coupons', 'custom_delete_nonce'); ?>
<input type="submit" class="button" value="Delete Expired Coupons" onclick="return confirm('Are you sure you want to delete all expired coupons?');" />
</form>
<?php
// Display a notice if expired coupons were deleted.
if (isset($_REQUEST['custom_deleted']) && $_REQUEST['custom_deleted'] === 'true') {
echo '<div class="updated"><p>Expired coupons deleted successfully.</p></div>';
}
}
}
// Redirect with a message after deletion.
add_action('admin_init', 'custom_delete_expired_coupons');
function custom_delete_expired_coupons() {
if (isset($_REQUEST['custom_action']) && $_REQUEST['custom_action'] === 'delete_expired_coupons' && check_admin_referer('custom_delete_expired_coupons', 'custom_delete_nonce')) {
delete_expired_coupons_action();
wp_redirect(add_query_arg(['custom_deleted' => 'true'], admin_url('edit.php?post_type=shop_coupon')));
exit;
}
}
@harmandeep-singh
Copy link

Change "expiry_date" to "date_expires"

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