Remove specific states on WooCommerce checkout BUT only in the shipping form

Viewed 115

I have this code which remove some States from the Billing and Shipping form in the checkout page. It works fine.

I need to remove the State but JUST in the "shipping form". Then the removed 'states' should be shown in the 'billing form'

I guess I need to use another hook than 'woocommerce_states'. But no sure which one.

function remove_my_states ($states) {
   unset ($states ['ES'] ['TF']);// tenerife
   unset ($states ['ES'] ['GC']);// gran canaria
   unset ($states ['ES'] ['CE']);// ceuta
   unset ($states ['ES'] ['ML']); // melilla
   unset ($states ['ES'] ['PM']); // baleares
   return $states;
   }
 
add_filter ('woocommerce_states', 'remove_my_states');
1 Answers

Your question is not that obvious because with the current hook you are using you cannot distinguish between the fields. What you can do as a workaround is use the woocommerce_form_field_$args['type'] filter hook.

The callback function uses $field which contains all HTML from <p> to the closing </p> HTML tag, so we have the ability to rewrite the entire output of this through our function.

So you get:

function filter_woocommerce_form_field_state( $field, $key, $args, $value ) {
    // Checkout page only
    if ( ! is_checkout() ) return $field;
    
    // Only for shipping
    if ( $key == 'shipping_state' ) {
        // Replace all occurrences of the search string with the replacement string
        $field = str_replace( '<option value="CE" >Ceuta</option>', '', $field );
        $field = str_replace( '<option value="ML" >Melilla</option>', '', $field );
        $field = str_replace( '<option value="PM" >Baleares</option>', '', $field );
        // Etc..
    }
    
    // Do something
    return $field;
}
add_filter( 'woocommerce_form_field_state', 'filter_woocommerce_form_field_state', 10, 4 );

Might come in handy: /woocommerce/i18n/states.php

More info: How should I change the woocommerce_form_field HTML Structure?

Related