Are you looking to offer your customers more shipping options? This code snippet allows you to automatically add distinct fees based on the specific flat rate shipping method selected by the customer.
add_action( 'woocommerce_cart_calculate_fees', 'ts_flat_rate_based_fee', 20, 1 ); function ts_flat_rate_based_fee( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' ); if( in_array( 'flat_rate:2', $chosen_shipping_methods ) ) { $fee = array( 'text' => __( "Pickup costs", "woocommerce" ), 'amount' => 12 ); } elseif ( in_array( 'flat_rate:4', $chosen_shipping_methods ) ) { $fee = array( 'text' => __( "Home delivery costs", "woocommerce" ), 'amount' => 24 ); } if( isset($fee) ) { $cart->add_fee( $fee['text'], $fee['amount'], false ); } }
Output
The provided code snippets, add a fee that depends on the chosen shipping method in the cart. Specifically, if the customer selects “Flat Rate 2,” a fee for pickup costs is added. These fees are calculated dynamically and displayed during the checkout process.
Sometimes you might also be required to add fee based on product category and shipping method in WooCommerce which will add extra costs based on certain parameters.