Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to delete a coupon Programmatically in WooCommerce?

While coupon deletion can be done manually from the Marketing >Coupons in WooCommerce, why do we need to delete a coupon programmatically? For an online store with larger catalogs, you might want to remove a coupon after a certain number of uses, deleting expired coupons, or when certain products are in the cart. This automation can save you time and effort compared to manually adjusting settings in the WooCommerce dashboard.

In this post, we will guide you to delete a coupon programmatically in WooCommerce based on different conditions as listed below:

  1. Delete all coupon codes created before a certain date.
  2. Delete all coupon codes that are expired & have 0 uses.
  3. Delete a single coupon.
  4. Delete multiple coupons.

Where to Add Custom Code in WooCommerce?

It is advisable to add the code snippets to the functions.php file of your child theme. Access the file directly from Appearance->Theme File Editor->Locating the child theme’s functions.php from the right sidebar. You can also access it from your theme’s directory file. Insert the following code snippet in functions.php. The alternative & easy option is to install & activate the Code Snippets plugin. You can then add the code as a new snippet via the plugin.

4 Ways to delete a coupon Programmatically in WooCommerce?

1. Delete all coupons created before a certain date in WooCommerce

Let’s consider an online store that offers one-time use coupon codes through automatically generated coupons. As a result, your database would have been accumulated with thousands of coupons. In such cases, the below code snippets help to delete outdated coupons that were created before a certain date. For e.g delete all coupons created before Jan 2022. It ensures that only the most recent and relevant promotions are available and accessed by users, avoiding potential errors or misunderstandings.

$target_date = strtotime('01/01/2022'); // Set the target date to 1st January 2022

// Get all coupons created before the target date
$args = array(
    'posts_per_page' => -1,
    'post_type'      => 'shop_coupon',
    'post_status'    => 'publish',
    'date_query'     => array(
        'before' => date('Y-m-d', $target_date),
    ),
);

$coupons = get_posts($args);

if (!empty($coupons)) {
    foreach ($coupons as $coupon) {
        wp_delete_post($coupon->ID, true);

        // Optionally, log or display a message
        error_log('Coupon ID ' . $coupon->ID . ' deleted because it was created before ' . date('Y-m-d', $target_date));
    }
}

This code retrieves all coupons created before the specified target date (1st January 2022) and deletes them. Adjust the $target_date variable to your desired date.

Output

In the following output, you can observe the deletion of all coupon codes generated before a specific date.

2. Delete all coupon codes that are expired & have 0 uses in WooCommerce

Considering events, online stores generate a huge number of one-time-use coupons. These coupons are automatically generated in bulk and are set to expire shortly after the corresponding promotion period ends. After the promotion period, there could be a significant number of expired and unused coupons still present in the system. so the below code will help to delete all coupons that are expired and coupons that are unused.

Read Related: How to Delete Coupon Code Programmatically in Easy Digital Downloads?
// Get all coupons
$coupons = get_posts(array(
    'post_type'     => 'shop_coupon',
    'posts_per_page' => -1,
));

foreach ($coupons as $coupon) {
    // Get the coupon data
    $coupon_data = new WC_Coupon($coupon->post_title);

    // Check if the coupon exists
    if (!empty($coupon_data->id)) {
        // Get the expiration date
        $expiration_date = strtotime($coupon_data->get_date_expires());

        // Get the usage count
        $usage_count = $coupon_data->get_usage_count();

        // Check if the coupon is expired and unused
        if ($expiration_date && $expiration_date < time() && $usage_count === 0) {
            // Delete the coupon
            wp_delete_post($coupon_data->id);

            // Optionally, log or display a message
            error_log('Coupon ' . $coupon_data->get_code() . ' deleted because it is expired and unused.');
        }
    }
}

Output

The following output shows that all the expired and unused coupons are deleted.

3. Delete a single coupon Programmatically in WooCommerce

The code snippets below help to delete a single coupon. Replace your actual coupon code instead of ‘christmas’ in the code given below.

$coupon_data = new WC_Coupon('christmas');
if (!empty($coupon_data->id)) {
    wp_delete_post($coupon_data->id);
}

Output

When a customer manually enters the coupon code, a notice message is displayed that the coupon code doesn’t exist.

How to delete a coupon Programmatically in WooCommerce? - Tyche Softwares
How to delete a coupon Programmatically in WooCommerce? - Tyche Softwares
How to delete a coupon Programmatically in WooCommerce? - Tyche Softwares

Are you offering services and looking for a dependable way to take BOOKINGs online?

Booking & Appointment plugin for WooCommerce is filled with service business-friendly booking features to bridge your customer needs and your offerings, simplify the booking experience, and improve customer experience.

Code Explanation

Creating a Coupon Object:

  • WC_Coupon is a class in WooCommerce that represents a coupon. Here, a new instance of the WC_Coupon class is created, and it’s assigned to the variable $coupon_data.
  • The parameter ‘christmas’ is passed to the constructor, indicating that we want to work with the coupon named ‘christmas’.

Checking if the Coupon Exists:

This conditional statement checks if the id property of the $coupon_data object is not empty. In WooCommerce, a coupon’s id is a unique identifier assigned to it.

Deleting the Coupon:

  • If the coupon exists (as determined by the if condition), the wp_delete_post function is called to delete the coupon post.
  • The $coupon_data->id retrieves the unique identifier of the coupon, and this identifier is passed as an argument to wp_delete_post to specify which post (coupon) to delete.

4. Delete multiple coupons Programmatically in WooCommerce

If you want to delete multiple coupons, you can use an array to store coupon codes and then loop through the array to delete each coupon. Here’s the code to delete multiple coupons:

$coupon_codes = array('COUPON_1', 'COUPON_2', 'COUPON_3');

foreach ($coupon_codes as $coupon_code) {
    $coupon_data = new WC_Coupon($coupon_code);
    
    if (!empty($coupon_data->id)) {
        wp_delete_post($coupon_data->id);
    }
}

Conclusion

This post guides you to delete a coupon programmatically under different conditions. Alternatively, you can also apply coupon programmatically in WooCommerce which eliminates the need for customers to remember or manually input coupon codes.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x