如何获取WooCommerce国家选择下拉列表?

7
我想在网站上某个地方显示WooCommerce国家列表。我该如何获取像图像中这样的国家列表?
4个回答

20

通过在任何您想要的地方拥有以下代码,您可以实现这一点。

global $woocommerce;
    $countries_obj   = new WC_Countries();
    $countries   = $countries_obj->__get('countries');
    echo '<div id="my_custom_countries_field"><h2>' . __('Countries') . '</h2>';

    woocommerce_form_field('my_country_field', array(
    'type'       => 'select',
    'class'      => array( 'chzn-drop' ),
    'label'      => __('Select a country'),
    'placeholder'    => __('Enter something'),
    'options'    => $countries
    )
    );
    echo '</div>';
我已经测试了同样的代码,并将其用于一个简码中,然后在产品描述中使用了该简码。
请告诉我这对您是否有效。

您的代码显示了所有国家。但是我想要显示我在设置页面中指定的特定国家(销售给特定国家)。 - Jagankumar
将这些国家以键值对的形式存储在数组中(键将成为下拉选项的值,值将显示为该选项的文本),并将其分配给代码中的$countries变量。 - Domain
2
woocommerce_form_field有一个type => country参数,这正是您要寻找的内容。请参考Braj Kishor Sah的回答。 - honk31

12

这里是非常简单和精简的代码:

global $woocommerce;    
woocommerce_form_field( 'billing_country', array( 'type' => 'country' ) );

2
如果$key设置为'shipping_country'(就像示例中一样),它将提取商店将要运送到的所有国家。如果设置为其他内容,它将提取所有允许的国家列表(可在@woocommerce->settings->general中进行调整)。整个woocommerce_form_field函数在此处 - honk31

4
如果您想要自定义国家,可以将以下代码添加到您的function.php文件中:
add_filter( 'woocommerce_checkout_fields', 'add_custom_select_country' );
function add_custom_select_country( $fields ) {
    $fields['billing']['billing_select_country'] = array(
        'type'      => 'select',
        'required'  => true,
        'clear'     => false,
        'options'   => array(
        'country'   => __('Country', 'woocommerce' ),
        'fr'        => __('France', 'woocommerce' ),
        'gb'        => __('United Kingdom', 'woocommerce' ),
        'ru'        => __('Russian', 'woocommerce' )
    )
);
return $fields;
}

2

我的做法是这样的:

$wc_countries = new WC_Countries();
$countries = $wc_countries->get_countries();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接