Reset previous chosen shipping method in Woocommerce checkout page
Currently, I am clearing the default shipping selection method using this filter:
add_filter( 'woocommerce_shipping_chosen_method', '__return_false', 99);
However, this only clears it during the initial session of the customer. Once the customer chooses an option even once, it remembers the selection for the future.
I am trying to get the checkout to force the customer to pick a shipping option every time they visit the checkout even in the same session. Is it possible to run this filter every time the checkout page is loaded?
Solution 1:
You can reset the last chosen shipping method using in checkout page (for logged in customers):
delete_user_meta( get_current_user_id(), 'shipping_method' );
And also remove the chosen shipping method from session data:
WC()->session->__unset( 'chosen_shipping_methods' );
In a hooked function like:
add_action( 'template_redirect', 'reset_previous_chosen_shipping_method' );
function reset_previous_chosen_shipping_method() {
if( is_checkout() && ! is_wc_endpoint_url() && is_user_logged_in()
&& get_user_meta( get_current_user_id(), 'shipping_method', true ) ) {
delete_user_meta( get_current_user_id(), 'shipping_method' );
WC()->session->__unset( 'chosen_shipping_methods' );
}
}
Or you can also set a default shipping method for everybody in checkout page:
add_action( 'template_redirect', 'reset_previous_chosen_shipping_method' );
function reset_previous_chosen_shipping_method() {
if( is_checkout() && ! is_wc_endpoint_url() && is_user_logged_in() ) {
WC()->session->set( 'chosen_shipping_methods', array('flat_rate:14') );
}
}
To find out the shipping methods rate Ids to be used, you can inspect the shipping method radio buttons in cart or checkout pages, with your browser inspector like:
Code goes on function.php file of your active child theme (or active theme). It should works.