Remove checkout fields with Woocommerce depending on one of several shipping methods


I’ve added the following code to
remove some checkout fields in case a particular shipping method is chosen and also make it work when you change the shipping method on the checkout page.

add_filter( 'woocommerce_checkout_fields', 'xa_remove_billing_checkout_fields' );
function xa_remove_billing_checkout_fields( $fields ) {
    // change below for the method
    $shipping_method ='local_pickup:1'; // Here I want to specify an array of shipping methods
    // change below for the list of fields
    $hide_fields = array( 'billing_address_1', 'billing_address_2', 'billing_city', 'billing_state', 'billing_postcode' );

    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    // uncomment below line and reload checkout page to check current $chosen_methods
    // print_r($chosen_methods);
    $chosen_shipping = $chosen_methods[0];

    foreach($hide_fields as $field ) {
        if ($chosen_shipping == $shipping_method) {
            $fields['billing'][$field]['required'] = false;
            $fields['billing'][$field]['class'][] = 'hide';
        $fields['billing'][$field]['class'][] = 'billing-dynamic';

    return $fields;

add_action( 'wp_footer', 'cart_update_script', 999 );
function cart_update_script() {
    if (is_checkout()) :
        .hide {display: none!important;}
        jQuery( function( $ ) {

            // woocommerce_params is required to continue, ensure the object exists
            if ( typeof woocommerce_params === 'undefined' ) {
                return false;

            $(document).on( 'change', '#shipping_method input[type="radio"]', function() {
                // change local_pickup:1 accordingly 
                $('.billing-dynamic').toggleClass('hide', this.value == 'local_pickup:1');

I was wondering how to make this work for an array of shipping methods. Suppose I want to make this work for flat_rate:2 as well, how could I elegantly loop the array to hide the fields an all shipping method of the array.

BarrieO 3 years 2020-06-06T08:10:22-05:00 0 Answers 98 views 0

Leave an answer