Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Frontend Snippets][Add a surcharge to cart and checkout] Add a standard $ value surcharge to all transactions
/**
* Add a standard $ value surcharge to all transactions in cart / checkout
*/
add_action( 'woocommerce_cart_calculate_fees','wc_add_surcharge' );
function wc_add_surcharge() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$county = array('US');
// change the $fee to set the surcharge to a value to suit
$fee = 1.00;
if ( in_array( WC()->customer->get_shipping_country(), $county ) ) :
$woocommerce->cart->add_fee( 'Surcharge', $fee, true, 'standard' );
endif;
}
@mkelley15

This comment has been minimized.

Copy link

@mkelley15 mkelley15 commented Jan 18, 2019

Is there a way to make this fee multiply per quantity of items in the cart?

After asking this question, I came across a few threads that might be helpful to others:
https://stackoverflow.com/questions/26240591/add-a-fee-to-woocommerce-per-product-based-on-category
https://gist.github.com/ChromeOrange/9200450

In combination with the 2 links above, I created the below code. https://gist.github.com/mkelley15/3f8d4bab3d6171820a0943a10eeefa89

 //Add Paypal 2.9%+0.50 surcharge to Woocommerc cart / checkout
 function df_add_handling_fee( $cart_object ) {
 global $woocommerce;
 $spfee = 0.00; // initialize special fee
 $spfeeperprod = 0.50; //special fee per product
 $percentage = 0.029;

 //Getting Cart Contents. 
 $cart = $woocommerce->cart->get_cart();
 //Calculating Quantity
 foreach($cart as $cart_val => $cid){
 $qty += $cid['quantity']; 
 }
 foreach ( $cart_object->cart_contents as $key => $value ) {

$proid = $value['product_id']; //get the product id from cart
//$quantiy = $value['quantity']; //get quantity from cart
$itmprice = $value['data']->price; //get product price

$terms = get_the_terms( $proid, 'product_cat' ); //get taxonamy of the prducts
if ( $terms && ! is_wp_error( $terms ) ) :
    foreach ( $terms as $term ) {
            $spfee =  (($woocommerce->cart->cart_contents_total * $percentage)+($qty * $spfeeperprod));
    }
  endif;  
 }

 if($spfee > 0 ) {
$woocommerce->cart->add_fee( 'Handling Fee', $spfee, true, 'standard' );
 }
 }
 add_action( 'woocommerce_cart_calculate_fees', 'df_add_handling_fee' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment