Search code examples
phpwordpresswoocommercecart

Set "flat rate" shipping method as default in woocommerce


I have a woocommerce website and I have set 2 shipping methods:

  • Flat Rate
  • Local pickup

I would like to set the "Flat rate" shipping method as default (selected) in the cart or checkout page.


Solution

  • 1) You can use the following code (to set "flat rate" shipping method as default) In cart page:

    add_action( 'woocommerce_before_cart', 'set_default_chosen_shipping_method', 5 );
    function set_default_chosen_shipping_method(){
        //
        if( count( WC()->session->get('shipping_for_package_0')['rates'] ) > 0 ){
            foreach( WC()->session->get('shipping_for_package_0')['rates'] as $rate_id =>$rate)
                if($rate->method_id == 'flat_rate'){
                    $default_rate_id = array( $rate_id );
                    break;
                }
    
            WC()->session->set('chosen_shipping_methods', $default_rate_id );
        }
    }
    

    Code goes in function.php file of your active child theme (active theme or in any plugin file).

    Tested and Works in WooCommerce 3+


    2) You can also reorder the shipping rates in your shipping zones settings (but it doesn't really works as the last chosen shipping method take the hand).