Apply a coupon programmatically in Woocommerce
🔥🎉🛒 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! 🗣️🤝