WooCommerce is a powerful eCommerce plugin for WordPress that allows you to create an online store and sell products or services. With WooCommerce, you can offer discounts to your customers to increase sales and promote loyalty. In this blog, we will show you how to add a custom discount to WooCommerce checkout programmatically.
Step 1: Create a Child Theme or Custom Plugin
Before we start, it’s important to note that any custom code should not be added directly to the WooCommerce plugin or your theme’s file. This is because any updates to the WooCommerce plugin or theme will overwrite the changes made to the code.
Therefore, it is recommended to create a child theme or a custom plugin to add the custom discount code. This ensures that your changes are not lost when updating your site.
Step 2: Add Custom Discount Code
Once you have created a child theme or custom plugin, you can start adding the custom discount code. The first step is to use the “woocommerce_cart_calculate_fees” action hook. This hook is used to add custom fees or discounts to the cart total.
Here’s an example code snippet to add a custom discount of $10 to the cart total:
add_action( 'woocommerce_cart_calculate_fees', 'wk_add_custom_discount' ); function wk_add_custom_discount( $cart ) { $discount_amount = 10; // replace with your desired discount amount $cart->add_fee( 'Custom Discount', -$discount_amount ); }
This code adds a custom discount of $10 to the cart total. You can customize the discount amount and the fee label according to your needs.
Step 3: Save Changes and Test
Once you have added the custom discount code, save the changes to your child theme or a custom plugin. Now, go to your WooCommerce checkout page and test the custom discount.
If everything is working correctly, you should see the custom discount applied to the cart total.
Custom Discount Cart Page:

Custom Discount Checkout Page:

Conclusion: In conclusion, adding a custom discount to WooCommerce checkout programmatically is a simple process.
By using the “woocommerce_cart_calculate_fees” action hook, you can add a custom discount to the cart total. Remember to always add custom code to a child theme or custom plugin to avoid losing changes when updating your site.
Support
Still, have any issues feel free to add a ticket and let us know your views to make the code better https://webkul.uvdesk.com/en/customer/create-ticket/ also you can contact us at [email protected].
Thanks for Your Time! Have a Good Day!
Be the first to comment.