By adding fees based on certain parameters, store owners can better reflect real-world costs associated with certain products and shipping methods. The below code snippet can help to add fees based on product category and chosen shipping method in WooCommerce.
add_action( 'woocommerce_cart_calculate_fees','ts_custom_category_fee'); function ts_custom_category_fee( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; $chosen_shipping_method_id = WC()->session->get( 'chosen_shipping_methods' )[0]; $chosen_shipping_method = explode(':', $chosen_shipping_method_id)[0]; // Set HERE your categories (can be term IDs, slugs or names) in a coma separated array $categories = array('50'); $fee_amount = 0; // Loop through cart items foreach( $cart->get_cart() as $cart_item ){ if( has_term( $categories, 'product_cat', $cart_item['product_id']) ) $fee_amount = 35; } // Only for Local pickup chosen shipping method if ( strpos( $chosen_shipping_method_id, 'free_shipping' ) !== false || strpos( $chosen_shipping_method_id, 'filters_by_cities_shipping_method' ) !== false ) { // Loop though each cart items and set prices in an array foreach ( $cart->get_cart() as $cart_item ) { // Get product id $product_id = $cart_item['product_id']; // Quantity $product_quantity = $cart_item['quantity']; // Check for category if ( has_term( $special_fee_cat, 'product_cat', $product_id ) ) { $total += $fee_per_prod * $product_quantity; } } // Adding the fee if ( $fee_amount > 0 ){ // Last argument is related to enable tax (true or false) WC()->cart->add_fee( __( "Additional Fees", "woocommerce" ), $fee_amount, false ); } } }
Output
When products from the ‘Electronic’ category are added to the cart and if the chosen shipping method is ‘Free shipping’ an extra fee of $35 is added to the cart totals.
Alternatively, you can also add WooCommerce Checkout fees based on shipping method and payment method.