There is a good way to hook into the shipping methods of your store and modify them according to various factors.
In the case that I will describe here, you will see how you can change the amount of your Flat Rate shipping method depending on the sub-total in your cart.
The filter we are going to use is woocommerce_package_rates
This filter will return all the information about your methods and is triggered on the cart and the checkout page.
First, you should use it to get details about your methods and know which one to target.
Add the following in your functions.php:
add_filter( 'woocommerce_package_rates', 'jemarea_shipping_methods_check', 10, 2 ); function jemarea_shipping_methods_check( $rates, $package ) { $ret = "TESTING RATES: <br><br>"; foreach( $rates as $idx=>$value ) { $ret .= "- " . $idx . "<br>"; } echo $ret; return $rates; }
And check you Cart page.
If you don’t see anything there, you can check the source code and see if it appears there.
Now, it could be that you don’t see anything of it.
In this case, you have another way of checking the needed information:
Look at the front-end on your Cart page and use the browser’s inspection tool to read the radio button of the shipping mehtod you would like to target.
This will be something of the sort:
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate9" value="flat_rate:3" class="shipping_method">
Remember the value part, you will need it.
Now we are going to add some code to our filter:
add_filter( 'woocommerce_package_rates', 'jemarea_shipping_on_price', 10, 2 ); function jemarea_shipping_on_price( $rates, $package ) { $total = WC()->cart->cart_contents_total; if( $total <= 250 ) { $rates['flat_rate:3']->cost = 25; } elseif ( $total > 250 && $total <= 500 ) { $rates['flat_rate:3']->cost = 50; } else { $rates['flat_rate:3']->cost = 100; } return $rates; }
What are we doing here?
Depending on the Sub-Total Amount of our cart we are changing the amount charged for the Flat Rate shipping method.
You can see probably imagine how far this can go. You can use any of the information from the Cart to change nearly any of the information from the shipping methods.
You can even deactivate some of the methods using this:
unset( $rates['flat_rate:8']
Have fun with coding!
Leave a Reply