I want to display woocommerce countries list some where on website. how can i get the country list like this as image?
How to get woocommerce country select dropdown?
Asked Answered
Yes you can achieve this by having the following code where ever you want
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>';
I have tested the same and have used the same code in a shortcode and used that shortcode on product description
Let me know if this works for you too.
your code displays all countries. but i would like to display specific countries which i have specified on settings page( sell to specific countries) –
Mace
Get those countries in an array format with key(this will become dropdown option's value) and value(this will appear as text in dropdown for that option) pair and assign the same to the $countries variable in the code. –
Latoria
woocommerce_form_field
has a type => country parameter and this one does exaclty, what you are looking for.. see Braj Kishor Sah's answer.. –
Rickyrico You can use
(new WC_Countries())['countries']
as well instead of using the magic __get
explicitely –
Mateusz Here is very simple and minified code:
global $woocommerce;
woocommerce_form_field( 'billing_country', array( 'type' => 'country' ) );
if $key is set to 'shipping_country' (like in the example), it will pull out all countries, that the shop will ship to. if it is set to something else, it will pull out a list of all allowed countries (both adjustable @woocommerce->settings->general). the whole
woocommerce_form_field
function is here –
Rickyrico You can add this to your function.php if you want custom country :
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;
}
My approach was this:
$wc_countries = new WC_Countries();
$countries = $wc_countries->get_countries();
© 2022 - 2024 — McMap. All rights reserved.