WooCommerce: How to set a default table-rate shipp

2019-09-11 12:53发布

问题:

I have 2 shipping methods defined:

  1. Table Rates - Priority 1
  2. Local Pickup - Priority 2

Within Table Rates, I have 3 options:

  1. Registered Australian Post (2 to 8 Business Days): $6.50
  2. Tracking and Freight Insurance: $7.25
  3. Nation-Wide Delivery (5 to 12 Business Days): $1.40

All orders that fall within the Local Table Rate area are presented with these 3 options and by default, Option 3 is selected ( I assume because it is the cheapest)

It defaults the priority to table rates but you can't define priority within the actual table rates. I want the default option to be Option 1: Registered Australian Post (2 to 8 Business Days)

I have discovered that the default shipping method is set here:

WC()->session->[chosen_shipping_methods] => a:1:{i:0;s:17:"table_rate-5 : 70";}

and apparently can be accessed and modified using the following two methods:

WC()->session->get('chosen_shipping_methods');
WC()->session->set('chosen_shipping_methods', $chosen_method);

BUT, I can get the current chosen_shipping_methods I just can't set a new one.

I'm trying to set it using the action woocommerce_shipping_method_chosen but it's not working

Can anyone guide me to what I should be looking at?

回答1:

by only looking on your website and not looking at the code, I'm guessing this might be what you want...

add_action( 'template_redirect', 'reigel_chosen_shipping_methods' );

function reigel_chosen_shipping_methods(){
    remove_action(current_filter(), __FUNCTION__);
    WC()->session->set( 'chosen_shipping_methods', array('table_rate-7 : 72') );
}


回答2:

You can reorder shipping methods via the admin dashboard. Goto Woocommerce > Shipping > Shipping Methods and change the order using drag and drop.



回答3:

This is what I ended up using which worked as required:

/*=Use the shipping method filter to set the "selected" shipping method to 
 * the first (default) method in the list
**************************************************************************/
function oley_reset_default_shipping_method( $method, $available_methods ) {

    $method = key($available_methods);
    return $method;

}
add_filter('woocommerce_shipping_chosen_method', 'oley_reset_default_shipping_method', 10, 2);

(NOTE: This worked because the shipping rate I wanted was actually the first in the list but just wasn't being selected by default)