php - Add shipping method by shipping zone in WooCommerce
Get the solution ↓↓↓I want to add a particular shipping method when customer address is within particular shipping zone. While searching through Stackoverflow I found a lot of snippets removing shipping methods based on some criteria but I found none adding shipping methods. Desired shipping method exists in options, it is disabled by default, it's a flatrate with ID 7. Here's what I tried:
add_filter( 'woocommerce_package_rates', 'add_shipping_method_based_on_shipping_zone', 10, 2 );
function add_shipping_method_based_on_shipping_zone( $rates, $package )
{
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$shipping_zone = wc_get_shipping_zone( $package );
$zone_id = $shipping_zone->get_id();
if ( $zone_id == 3) {
// some magic here to add an existing shipping method which was disabled in shipping options
$rates[] = 'flat_rate:7'; // this does not work, looks like I have to insert all shipping method properties as well
}
return $rates;
}
Zone matching logics are working as expected but I was not able to figure out how I can add an existing shipping method to $rates object. Also I was not able to print $rates and $package contents through 'woocommerce_package_rates' filter although it seemed to work some time ago. So any suggestion how I can print these objects on cart page is welcome.
Answer
Solution:
When a shipping method is disabled it is not present in$rates
, so an option is to enable it and using some reverse logic
function filter_woocommerce_package_rates( $rates, $package ) {
// Shipping zone
$shipping_zone = wc_get_shipping_zone( $package );
// Get zone ID
$zone_id = $shipping_zone->get_id();
// NOT equal
if ( $zone_id != 3 ) {
// Unset a single rate/method
unset( $rates['flat_rate:7'] );
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: foreach() argument must be of type array|object, null given
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.