Skip to content
Advertisement

Custom shipping rates programmatically in Woocommerce

I Want to calculate custom shipping rates based on cart amount for woocommerce, My requirement as follows,

Cart amount

  1. 0-10 => £4.99 (shipping_rate_id = flat_rate:12),
  2. 10-20 => £3.99 (shipping_rate_id = flat_rate:13),
  3. 20-30 => £2.99 (shipping_rate_id = flat_rate:14),
  4. 30-40 => £1.99 (shipping_rate_id = flat_rate:15),
  5. over 40 => Free Shipping (shipping_rate_id = flat_rate:17)

Note : We Do not calculate shipping charge for tobacco category. If someone buy tobacco item, Tobacco item price do not use for shipping charge calculation. To accomplish this all the tobacco items added to free shipping class (id = 150).

Setup custom query to accomplish above requirement, but it does not work as I expected

JavaScript

Above code not perfect for all the scenarios, please help me.

Advertisement

Answer

If you know the value of shipping_rate_id for each shipping method it means that in the WooCommerce plugin (WooCommerce > Settings > Shipping > Shipping Zones > Edit > Shipping Methods) you have already created and assigned a shipping cost (or free) for each individual shipping method.

So you don’t need to change the cost of each one again.

Also for free shipping the shipping rate id will be free_shipping:17 instead of flat_rate:17.
Unless you have created a zero cost shipping method (flat rate instead free shipping).

The working code will be:

JavaScript

The code has been tested and works. The code goes into your theme’s functions.php file.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement