WooCommerce Add Fee With A Coupon

WooCommerce checkout showing a fee has been added by a coupon code

Pre-Requisites

The coupon code must exist.

How To Implement This Solution?

Simply copy the pre-coded solution to your active theme’s functions.php or preferably the Code Snippets Plugin.

About this Solution

Yes, you read the title correctly, weird I know!

This snippet was requested by one of the Facebook Community members.

This code snippet checks if a user defined coupon code has been applied to the order. If it has, a percentage based fee is added to the order with the label “Coupon Fee”.

				
					/**
 * Snippet Name:	WooCommerce Add Fee With A Coupon
 * Snippet Author:	ecommercehints.com
 */

add_action( 'woocommerce_cart_calculate_fees','ecommercehints_add_fee_with_coupon' );
function ecommercehints_add_fee_with_coupon() {
	global $woocommerce;
	
	if (is_admin() && ! defined('DOING_AJAX')) return;
	
	$coupon_id = 'Add10%'; // The specific coupon code to add the fee (this must exist)
	
	if(!in_array($coupon_id, $woocommerce->cart->get_applied_coupons())) {
		$percentage = 0.1;// The percentage fee, 0.1 being 10%
		$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
		$woocommerce->cart->add_fee( 'Coupon Fee', $surcharge, true, '' ); // The fee label, amount, taxable status, and tax class
	}
}
				
			
WooCommerce Conversion Rate Optimisation (CRO) eBook
100 WooCommerce Conversion Rate Optimisation Tips

Leave a Reply

If you are going to write code in the comments, please wrap it between code tags.

Your email address will not be published. Required fields are marked *

Other Recent Guides

Subscribe To Emails

Get exclusive WooCommerce tips that I only share with email subscribers

Join hundreds of other subscribers