Last active
November 30, 2021 10:40
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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, '' ); | |
} | |
} | |
} |
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;
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.
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
Awesome, this works great! Is there a way to add the surcharge on a per product basis rather than by the entire cart contents?