I'm struggling with changing the shipping option selected default. The 'Free shipping' shipping option only shows up if the customer has the amount over $70 + in the cart. If the amount on the cart is less than $70 the shipping option will not show up on the shipping options.
If the customer has over $70 or more, the "Free shipping" option will show up and it should be a default selected shipping option.
I tried adding the following snippet but it seems not working for me or maybe there's a mistake on modifying the ID's(unsure).
add_action( 'woocommerce_before_cart', 'set_default_chosen_shipping_method', 5 );
function set_default_chosen_shipping_method(){
//
if( count( WC()->session->get('shipping_method_0')['rates'] ) > 0 ){
foreach( WC()->session->get('shipping_method_0')['rates'] as $rate_id =>$rate)
if($rate->method_id == 'free_shipping30'){
$default_rate_id = array( $rate_id );
break;
}
WC()->session->set('chosen_shipping_methods', $default_rate_id );
}
}
I got this snippet idea here
Thank you in advance!!
Your code contains some mistakes
WC()->session->get('shipping_method_0')['rates']
with WC()->session->get( 'shipping_for_package_0')['rates']
if($rate->method_id == 'free_shipping30'){
with if ( $rate->method_id == 'free_shipping' ) {
So you get:
function action_woocommerce_before_cart() {
// NOT empty (get)
if ( count( WC()->session->get( 'shipping_for_package_0')['rates'] ) > 0 ) {
// Loop through
foreach ( WC()->session->get('shipping_for_package_0')['rates'] as $rate_id => $rate ) {
// For free shipping
if ( $rate->method_id == 'free_shipping' ) {
$default_rate_id = array( $rate_id );
break;
}
}
// Set
WC()->session->set( 'chosen_shipping_methods', $default_rate_id );
}
}
add_action( 'woocommerce_before_cart', 'action_woocommerce_before_cart', 10, 0 );