Apply a coupon programmatically in Woocommerce

Cover Image for Apply a coupon programmatically in Woocommerce
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

🔥🎉🛒 Apply a Coupon Programmatically in WooCommerce: A Complete Guide 🛒🎉🔥

Are you looking to apply a coupon code programmatically in WooCommerce? 🤔💰

We've got you covered! In this guide, we'll walk you through the process step by step, providing easy solutions to common issues along the way. 💪💡

Scenario: Let's say you want to apply a 10% discount to a customer's order if the weight in their cart is over 100 lbs. How can you achieve this programmatically through the functions.php file? 🤷‍♀️

Step 1: Retrieve the Total Weight To get started, you need to modify the cart.php file to retrieve the total weight of all the products in the cart. This will allow us to determine if the weight condition is met. For example, you can add the following code to the woocommerce/cart/cart.php file:

global $total_weight;
$total_weight = $woocommerce->cart->cart_contents_weight;

Step 2: Apply the Discount Coupon Next, we're going to utilize the woocommerce_ajax_apply_coupon function to apply the discount coupon programmatically. Here's how you can do it:

add_action('woocommerce_before_cart_table', 'discount_when_weight_greater_than_100');
function discount_when_weight_greater_than_100() {
    global $woocommerce;
    global $total_weight;
    
    if( $total_weight > 100 ) {
        $coupon_code = 'YOUR_COUPON_CODE';
        
        if (!$woocommerce->cart->add_discount(sanitize_text_field($coupon_code))) {
            $woocommerce->show_messages();
        }
        
        echo '<div class="woocommerce_message"><strong>Your order is over 100 lbs, so a 10% Discount has been applied!</strong> Your total order weight is <strong>' . $total_weight . '</strong> lbs.</div>';
    }
}

Make sure to replace YOUR_COUPON_CODE with the actual code you want to apply.

Step 3: Remove the Discount Coupon Now, let's remove the discount coupon if the weight condition is not met. This prevents the coupon from being applied incorrectly. Add the following code to your functions.php file:

add_action('woocommerce_before_cart_table', 'remove_coupon_if_weight_100_or_less');
function remove_coupon_if_weight_100_or_less() {
    global $woocommerce;
    global $total_weight;
    
    if( $total_weight <= 100 ) {
        $coupon_code = 'YOUR_COUPON_CODE';
        $woocommerce->cart->get_applied_coupons();
        
        if (!$woocommerce->cart->remove_coupons(sanitize_text_field($coupon_code))) {
            $woocommerce->show_messages();
        }
        
        $woocommerce->cart->calculate_totals();
    }
}

Again, make sure to replace YOUR_COUPON_CODE with the actual coupon code.

That's it! You've successfully implemented a programmatic way to apply a coupon in WooCommerce based on weight conditions. 💪🎉

Feel free to customize the displayed message and tweak the code to fit your requirements. 😉

If you have any questions or need further assistance, feel free to reach out to us in the comments below. We're here to help! 🙌🤓

Now it's your turn! Have you ever implemented a discount coupon programmatically in WooCommerce? Share your experience in the comments and let's help each other grow! 🗣️🤝

👉 Full code, problem and solved


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello