I need to change the address fields to be 'required', when the user will select shipping method that is other than "local pickup".
I managed make it optional by default (local pickup is selected by default) using a filter, like this:
add_filter( 'woocommerce_checkout_fields', 'disable_required_address_shipping' );
function disable_required_address_shipping($fields ) {
if ( check_if_local_pickup() ) {
$fields['billing']['billing_address_1']['required'] = false;
$fields['billing']['billing_address_2']['required'] = false;
$fields['billing']['billing_city']['required'] = false;
}
return $fields;
}
function check_if_local_pickup() {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
if ($chosen_shipping == 'local_pickup') {
return true;
}
}
But I need to change it dynamically using an action.
I tried to look for a solution here and couldn't find one.
Is there any action that fires when changing shipping method?
Any ideas?
To fire an action when shipping method is changed you may use do_action( 'woocommerce_shipping_method_chosen', $chosen_method );
:
add_action( 'woocommerce_shipping_method_chosen', 'check_if_local_pickup', 10, 1 );
function check_if_local_pickup( $chosen_method ) {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
if ($chosen_shipping == 'local_pickup') {
return true;
}
}
References:
woocommerce_shipping_method_chosen (hookr.io)
Source code: class WC_Shipping (line 311)