The functionality of this code is that the shipping costs gets dynamically adjusted based on the quantity of the item selected in the cart. The cost is set to $3.5 if there is only one item in the cart and if there are multiple items, a maximum cost of $4.5 is set.
add_filter('woocommerce_package_rates', 'ts_custom_shipping_costs', 10, 2 ); function ts_custom_shipping_costs( $rates, $package ){ // Get cart items count $items_count = WC()->cart->get_cart_contents_count(); // Your cost settings $new_cost = $items_count > 1 ? 4.5 : 3.5; // Loop through shipping methods rates foreach ( $rates as $rate_key => $rate ){ $has_taxes = false; // Targeting "Flat rate" shipping methods if ( 'flat_rate' === $rate->method_id ) { $default_cost = $rates[$rate_key]->cost; $rates[$rate_key]->cost = $new_cost; $rate_conversion = $new_cost / $default_cost; // Taxes rate cost (if enabled) foreach ($rates[$rate_key]->taxes as $key => $tax){ if( $tax > 0 ){ $taxes[$key] = $tax * $rate_conversion; $has_taxes = true; } } if( $has_taxes ) $rates[$rate_key]->taxes = $taxes; } } return $rates; }
Output
In the below output, the quantity of the product added to the cart is one and when the ‘flat rate’ shipping method is chosen, the shipping costs is changed from its default value to the defined value in the code(i.e 3.50).
And when the product quantity is 4 or more than that, different shipping costs(for e.g. 4.50 here) are assigned when the flat rate shipping method is chosen.
You can also dynamically change all shipping methods cost to zero based on cart total in WooCommerce.