This PHP code for WooCommerce gives you the option to set a different shipping price when someone orders specific amount of products from a specific category.
For example : You are selling wine and other beverages in different categories. When a customer orders a quantity between 1 – 3 bottles of wine, we add $5 to the total shipping costs. If someone orders between 4 to 6 bottles of wine, we add $7 to the flat rate shipping costs.
In this example, the base rate for additional shipping costs is $5 and the recurring rate is $2 for every 3 additional items.
Any cost you set in the flat rate shipping method settings is also added. This setting could be zero or anything you like.
Copy and paste the code to the end of your child themes functions file or custom functionality/code snippets plugin.
- Line 6 set your category slug or array of comma separated category slugs when targeting more than 1 product category.
- Line 9 set your additional cost for every multiple. In this example its calculated for every 3 items.
- Line 33 set your base cost for the 1st 3 items. In this example its set at $5.
- Line 35 set your multiple. In this case its set at 3. $2 for every 3 items beyond the first 3.
Let’s explain the key functions in the downloadable code:
custom_shipping_cost_based_on_quantity_and_category Function :
– This is a custom function hooked into the
– It calculates and modifies the shipping rates based on the quantity and category of products in the order.
– It takes two parameters:
$rates (the existing shipping rates) and
$package (the contents of the cart).
- Variables Defined :
$wine_category_slug: It holds the slug of the category you want to apply specific shipping rules to (e.g., ‘wine’).
$additional_shipping_cost_per_3_bottles: This variable represents the additional shipping cost for every 3 bottles of wine.
- Calculating Total Quantity :
- The code loops through the cart contents to calculate the total quantity of products in the order.
- Checking for Wine Category :
- The code checks if the specified wine category is present in the order.
- Modifying Flat Rate Shipping :
- It selectively modifies the rates only for the “Flat Rate” shipping method.
- If the wine category is present, it calculates the additional shipping cost:
- For the first 1-3 bottles, a base cost of $5 is added.
- For every 3 bottles beyond the first 3, an additional $2 is added for each set of 3 bottles.
- Returning Modified Rates:
- The function returns the modified shipping rates.
This code allows you to customize the shipping costs based on the quantity and category of products in the cart, specifically targeting the “Flat Rate” shipping method. It ensures a base cost of $5 for the first 1 – 3 bottles and then adds $2 for every 3 bottles beyond the first 3, without capping the additional cost.