Skip to content

Instantly share code, notes, and snippets.

@pjv
Last active October 9, 2018 18:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjv/396dbbbf4d420a15ba88e97ce91b7f34 to your computer and use it in GitHub Desktop.
Save pjv/396dbbbf4d420a15ba88e97ce91b7f34 to your computer and use it in GitHub Desktop.
put into functions.php to make WooCommerce cart default to choosing the cheapest shipping option
// https://github.com/woothemes/woocommerce/issues/3641
// http://stackoverflow.com/questions/36300773/woocommerce-programmatically-changing-the-default-shipping-method
// guts of function straight copy of function get_default_method from WC v. 2.5.5 includes/class-wc-shipping.php
function plx_default_cheapest_shipping_method( $current_chosen_method, $available_methods ) {
$selection_priority = get_option( 'woocommerce_shipping_method_selection_priority', array() );
if ( ! empty( $available_methods ) ) {
// Is a method already chosen?
if ( ! empty( $current_chosen_method ) && ! isset( $available_methods[ $current_chosen_method ] ) ) {
foreach ( $available_methods as $method_key => $method ) {
if ( strpos( $method->id, $current_chosen_method ) === 0 ) {
return $method->id;
}
}
}
// Order by priorities and costs
$prioritized_methods = array();
foreach ( $available_methods as $method_key => $method ) {
// Some IDs contain : if they have multiple rates so use $method->method_id
$priority = isset( $selection_priority[ $method->method_id ] ) ? absint( $selection_priority[ $method->method_id ] ): 1;
if ( empty( $prioritized_methods[ $priority ] ) ) {
$prioritized_methods[ $priority ] = array();
}
$prioritized_methods[ $priority ][ $method_key ] = $method->cost;
}
ksort( $prioritized_methods );
$prioritized_methods = current( $prioritized_methods );
asort( $prioritized_methods );
return current( array_keys( $prioritized_methods ) );
}
return false;
}
add_filter('woocommerce_shipping_chosen_method', 'plx_default_cheapest_shipping_method', 10, 2);
@pjv
Copy link
Author

pjv commented Oct 7, 2016

Dunno why, but gist is forcing this file to have 8-char tabs even though I am trying to save with 2-char space indentation...

@hollysnails
Copy link

hello, do you have the code for the most expensive first? instead of cheapest? thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment