Modify Shipping Methods Programatically in Woocommerce


Modify Shipping Methods Programatically in Woocommerce is normal for any E-Commerce website build on WordPress using Woocomemrce. A lot of people gets confused when it comes to use woocommerce_package_rates filter on woocommerce to change shipping methods conditionally. I was one of them too. But woocommerce_package_rates do all stuff required to modify/remove shipping methods programatically.

Paste this code in theme_dir/functions.php

/**
  * Free Shipping if total is more then 200 USD excluding Coupons, Taxes or any other fees.
  *
  **/
add_filter( 'woocommerce_package_rates',  'modify_shipping_rate', 15, 2 );
function modify_shipping_rate( $available_shipping_methods, $package ){
    global $woocmmerce;

    // Cart Subtotal
    $total_coast = WC()->cart->get_cart_contents_total();
    if( $total_coast >= 200 ){
        // "free_shipping:1" is the Shipping Method ID
        
        if(isset($available_shipping_methods['free_shipping:1'])) {
            // Change Cost of Shipping Method
            $available_shipping_methods['free_shipping:1']->cost = 0;

            // Remove Shipping Method
            unset($available_shipping_methods['local_pickup:1']);
        }
    }
    return $available_shipping_methods;
}

Remember to clear cart and add products again, after adding woocommerce_package_rates filter.

You will have to change Shipping Method IDs according to your conditions. In this code it is free_shipping:1.

Find Shipping Methods ID

  1. Inspect Element on the Shipping Method.
  2. flat_rate:1 will be the Shipping Method ID as shown in the screenshot.

Modify Shipping Methods Programatically in Woocommerce is a simple method to complete your needs easily with less load

,

Leave a Reply

Your email address will not be published. Required fields are marked *