Loading...
12
227

How can I add Cash On Delivery extra fees in woocommerce

16/05/2021
3 minutes

tldr;
download directly the plugin from WordPress repository

https://wordpress.org/plugins/simple-cod-fee-for-woocommerce/

Most of the times Cash On Delivery is a paid service, so we need to add this extra fee in the checkout for the client to pay. If we don’t need any sophisticated solution that will slow down our website, it is best done without the need of a plugin. Let’s see how

add_action( 'woocommerce_cart_calculate_fees', function() {
	$cod_fee = 3;
    $chosen_gateway = WC()->session->get( 'chosen_payment_method' );

    if ( $chosen_gateway == 'cod' ) 
    {
    	$chosen_shipping_methods = wc_get_chosen_shipping_method_ids();

    	if ( !in_array('local_pickup', $chosen_shipping_methods) )
    	{    		
    		WC()->cart->add_fee( __('Cash on Delivery', 'woocommerce'), $cod_fee );
    	}
   }
} );

But let’s see exactly what we are writing

Line 1: First of all the hook that we need to use is woocommerce_cart_calculate_fees

Line 2: Here we simply define the extra fee we want to charge

Line 3: We get the chosen payment method and save it in variable $chosen_gateway

Line 5: With a simple if statement we check if the user has chosed Cash on Delivery (cod). Respectively, if we want to add extra cost to another payment method, we do the corresponding checks here. Default payment methods and their keys are the following

  • Cash On Delivery (cod)
  • Bank Transfer (bacs)
  • Cheque (cheque)
  • Paypal (paypal)

Line 7: Usually, we don’t want the extra fee when shipping method is Local Pickup.
Function wc_get_chosen_shipping_method_ids() returns in an array all active shipping methods (in some, more complicated websites, where an order can break down in multiple shipping methods this array would return more than one shipping method, but 99% of the time only on method would be returned.

Line 9: Here we check if selected shipping method IS NOT Locak Pickup (the id is local_pickup)

Line 11: Since user HAS NOT selected Local Pickup then we add the extra fee to the cart using WC()->cart->add_fee where the first parameter is the text that will be shown to the user as label and the second parameter is the extra fee.

tldr;
download directly the plugin from WordPress repository

https://wordpress.org/plugins/simple-cod-fee-for-woocommerce/

Do you want to comment?

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

83 Pixel. creative studio
Get Quote - EN