2019-02-01 00:26
浏览 106


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
        $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');

图片转代码服务由CSDN问答提供 功能建议

我认为这很容易,但我没有得到我想要的结果。 基本上我在加州和美国的woocommerce有2个国家。 我试图有条件地删除一个,我可以使用下面的代码执行此操作。 但是,当我从2个国家/地区转到1时,仍会显示下拉菜单。 我用以下代码注意到的一件奇怪的事情是,如果我进入我的Woocommerce设置,那么使用此代码删除的国家也会从“销售到特定国家/地区”选项中删除.... 确定发生了什么。 在此先感谢。

custom custom_woocommerce_countries_limit($ countries){
 / * 
将在此处设置条件,如果x 然后删除country 
 * / 
 unset($ countries ['CA']); 
 $ countries = array(
'US'=> __('United States','woocommerce')
返回$ countries; 

编辑:使用此挂钩可能接近答案,但是当我使用此挂钩时,状态不会 变成下拉列表...?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题