dougao1542 2019-02-01 00:26
浏览 108
已采纳

在Woocommerce允许的国家/地区,将州字段保留为下拉列表

I thought this would be easy but I'm not getting the results I want. Basically I have 2 countries in woocommerce CA and US. I'm trying to remove one conditionally, and I can do that with the following code below. However, when I go from 2 countries to 1, the dropdown menu still appears. An odd thing I'm noticing with the below code as well, is that if I go into my Woocommerce settings, then the country that is removed with this code is also removed from the "Sell to specific countries" options.... not sure what's going on. Thanks in advance.

add_filter( 'woocommerce_countries', 'custom_woocommerce_countries_limit');
function custom_woocommerce_countries_limit( $countries ) {     
        /*
        will place a conditional here if x then remove country
        */
        unset($countries['CA']);
        $countries = array(
            'US'  => __( 'United States', 'woocommerce' )
         ); 
    return $countries;
}

EDIT: Using this hook may be close to the answer, but when I use this one, The states don't turn into a dropdown...?

add_filter( 'woocommerce_countries_allowed_countries', 'custom_woocommerce_countries_limit');
  • 写回答

1条回答 默认 最新

  • doudao8283 2019-02-01 04:51
    关注

    You can use woocommerce_countries_allowed_countries filter hook, but you should need some additional code to force the state fields to be a state dropdown (select field):

    add_filter( 'woocommerce_countries_allowed_countries', 'filter_allowed_countries_conditionally');
    function filter_allowed_countries_conditionally( $countries ) {
        // will place a conditional here if x then remove country
        if( true ) {
            $countries = array( 'US'  => __( 'United States', 'woocommerce' ) );
        } else {
            $countries = array( 'CA'  => __( 'Canada', 'woocommerce' ) );
        }
        return $countries;
    }
    
    // Force billing state field type to be a dropdown
    add_filter( 'woocommerce_billing_fields', 'filter_billing_state_fields', 100, 1 );
    function filter_billing_state_fields( $fields ) {
        $fields['billing_state']['type'] = 'state';
        return $fields;
    }
    
    // Force shipping state field type to be a dropdown 
    add_filter( 'woocommerce_shipping_fields', 'filter_shipping_state_fields', 100, 1 );
    function filter_shipping_state_fields( $fields ) {
        $fields['shipping_state']['type'] = 'state';
        return $fields;
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统