Skip to content

Instantly share code, notes, and snippets.

@ChromeOrange
Last active November 30, 2021 10:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChromeOrange/9200450 to your computer and use it in GitHub Desktop.
Save ChromeOrange/9200450 to your computer and use it in GitHub Desktop.
Add a surcharge if certain products are in the cart, ideal for setup fees etc
/**
* Add a fixed surcharge to your cart / checkout based on products in cart
* Taxes, shipping costs and order subtotal are all included in the surcharge amount
*
* Change $fixed to set the surcharge to a value to suit
*
* Change in_array to !in_array to EXCLUDE the $countries array from surcharges
*
* Uses the WooCommerce fees API
* Add to theme functions.php
*/
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Setup an array or products that have a surcharge applied
// eg $setupfee_array = array( '7246' );
// or $setupfee_array = array( '7246','7500','4567' );
$setupfee_array = array( '7246' );
// The fee
$fixed = 5.00;
// loop through the cart looking for the free shpping products
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
if( in_array( $values['product_id'], $setupfee_array ) ) {
$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) + $fixed;
$woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, '' );
}
}
}
@matthewmsexton
Copy link

Awesome, this works great! Is there a way to add the surcharge on a per product basis rather than by the entire cart contents?

@HelloMyNameIsChris
Copy link

Line 31 adds the charge to the item and then adds that new total (item+surcharge) to the sub-total. Which charges them for the item twice.

I think it should just be $surcharge = $fixed;

@webgirl44
Copy link

Great help! Is there a way to multiply the surcharge by the quantity of that item in the cart? For example, if the surcharge is $10 and I add a quantity of 3 of that item to the cart the surcharge displays as $30.

@ChromeOrange
Copy link
Author

Corrected to remove 'standard' from add_fee based on woocommerce/woocommerce#6808

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment