Remove specific states of a country on Woocommerce Checkout

旧巷老猫 提交于 2019-12-11 11:04:43

问题


I am trying to find a way to remove a few US states from the "State" dropdown in WooCommerce checkout page.

List of states:

  1. Hawaii
  2. Alaska
  3. Armed Forces (AA)
  4. Armed Forces (AE)
  5. Armed Forces (AP)

What I have been doing so far:
I have been manually removing them as mentioned in this link. But this is not a good way, as the changes get overwritten every time WooCommerce is updated.

Alternative I found: On this link WooCommerce restrict shipping to states based on category, there's a way to set shipping states if specific condition is met. I am wondering if I can unset five states. This sounds more logical to me than setting 50 states. But unfortunately, I am not able to find anything useful.

Any ideas what could be a possible solution?


回答1:


The simplest way is to remove them them using the dedicated filter hook woocommerce_states this way:

add_filter( 'woocommerce_states', 'custom_us_states', 10, 1 );
function custom_us_states( $states ) {
    $non_allowed_us_states = array( 'AK', 'HI', 'AA', 'AE', 'AP'); 

    // Loop through your non allowed us states and remove them
    foreach( $non_allowed_us_states as $state_code ) {
        if( isset($states['US'][$state_code]) )
            unset( $states['US'][$state_code] );
    }
    return $states;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Then you can add some condition or make a custom settings page like in the threads below:

  • Disable some states if specific products are in cart in Woocommerce
  • US allowed States through Woocommerce custom setting page



回答2:


Best way of doing this would be using a filter, add this snippet in your themes functions.php

/**
 * Modify Woocommerce states array
 *
 * @param array $states, collection of all $states
 * @return array $states, modified array.
*/
add_filter( 'woocommerce_states', function( $states ){
    // Unset Hawaii
    unset( $states['US']['HI'] );

    return $states;
}, 999);

You can unset any states like this.



来源:https://stackoverflow.com/questions/53678249/remove-specific-states-of-a-country-on-woocommerce-checkout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!