1

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');
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
JPashs
  • 13,044
  • 10
  • 42
  • 65

1 Answers1

1

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?

7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
  • Not working in my site. I assume that the Theme I am using might cause this code to fail. I use Flatsome theme. This is checkout page of my site http://t12.d523.dinaserver.com/finalizar-compra/ – JPashs Feb 09 '22 at 08:02
  • @JPashs You can always try it by using a default theme. I can't take into account plugins or themes that influence my answer, since there are 1000+ of them. You could also try [How to debug in WooCommerce](https://stackoverflow.com/q/61740111/11987538). Regards – 7uc1f3r Feb 09 '22 at 09:15
  • I try it with other themes, but it does not work. I thing that the problem is that the problem is that your code try to match an 'option' element. In the 'Twenty Twenty-Two' theme the States is a search box build with ul->li elments (not an 'select->option elements) This is my site: https://latevabotiga.com/tienda/ – JPashs Feb 15 '22 at 18:27