I'm trying to hide checkout fields based on shipping method.
function premove_billing_checkout_fields($fields) {
global $woocommerce;
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
if( $chosen_shipping === 'local_pickup:20' ) {
unset($fields['billing']['billing_postcode']);
unset($fields['billing']['billing_state']);
unset($fields['billing']['billing_country']);
}
if( $chosen_shipping === 'wc_custom_shipping_pickpoint' ) {
unset($fields['billing']['billing_postcode']);
unset($fields['billing']['billing_address_1']);
unset($fields['billing']['billing_state']);
}
return $fields;
}
add_filter('woocommerce_checkout_fields',
'premove_billing_checkout_fields', 990 );
This code is working, but to hide the fields I need to refresh the page. How can I hide the fields using Ajax?
You don't need any Ajax to achieve this. The first function will make all necessary checkout fields not "required", as this is necessary to be able to conditionally show / hide checkout fields. The second function (mostly jQuery), will show / hide your desired fields depending on the chosen shipping method.
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This is tested and works on WooCommerce 3+