To dynamically set shipping costs based on the quantity of products ordered using a WooCommerce hook, you can install the code in this download folder which uses the
woocommerce_package_rates filter. in this example we :
- Set a base shipping cost of $5 in the WooCommerce > Settings > Shipping > Shipping Methods > Flat Rate > Flat rate Settings > Cost.
- In the code, set a base shipping cost of $10 for the first product and an additional $4 for each additional product after that.
- Set the product category to shoes so the code only adds the additional shipping cost to products in this category and doesn’t apply the extra cost to other products in the cart from other categories.
The following screenshot shows 2 products added to the cart. Only 1 is affected by this code because it only applies to the 2nd product which is in the shoes category.
The rate set in the shipping settings is $5. The code adds another $10 for the 1st item in category shoes and then $4 per item after that. The math is as follows :
$5 set in shipping settings
$10 set in the code for the 1st item in category shoes
$4 for the 2nd item
Total = $19
- The code works regardless of which category or categories are targeted in the code
- and regardless of what values you enter in the shipping settings and code.
- and applies to flat rate shipping.
Copy and paste the code to the end of your child themes functions file or custom functionality/code snippets plugin.
There’s 3 settings in the code you can swap out with your own to control which product categories are affected and values are used.
- Line 12. Set the shipping cost for the first product. Default is 10.
- Line 15. Set the additional shipping cost per product (after the first one). Default is 4.
- Line 23. Set the product category slug. Default is shoes.