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, '' );
}
}
}
@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