I am using wordpress and woocommerce. In checkout page, how do I restrict to only 1 country only? Say Australia.
Hello you can restrict to only one country by plugin settings
you can find in Woocommerce->Settings-> Genral tab
Just override the class by hook,
function woo_override_checkout_fields_billing( $fields ) {
$fields['billing']['billing_country'] = array(
'type' => 'select',
'label' => __('My New Country List', 'woocommerce'),
'options' => array('AU' => 'Australia')
);
return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'woo_override_checkout_fields_billing' );
function woo_override_checkout_fields_shipping( $fields ) {
$fields['shipping']['shipping_country'] = array(
'type' => 'select',
'label' => __('My New Country List', 'woocommerce'),
'options' => array('AU' => 'Australia')
);
return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'woo_override_checkout_fields_shipping' );
This will help you to show only 1 country in dropdown. Add this code to functions.php in theme.
Also maybe you want to sell to several countries but also you want to show ONLY the country where the user is connecting from (geolocated from IP address). Thus, in this way, a french user will only see France in the country dropdown, an australian user will only see Australia in the country dropdown and so on... Here is the code:
/**
* @param array $countries
* @return array
*/
function custom_update_allowed_countries( $countries ) {
// Only on frontend
if( is_admin() ) return $countries;
if( class_exists( 'WC_Geolocation' ) ) {
$location = WC_Geolocation::geolocate_ip();
if ( isset( $location['country'] ) ) {
$countryCode = $location['country'];
} else {
// If there is no country, then return allowed countries
return $countries;
}
} else {
// If you can't geolocate user country by IP, then return allowed countries
return $countries;
}
// If everything went ok then I filter user country in the allowed countries array
$user_country_code_array = array( $countryCode );
$intersect_countries = array_intersect_key( $countries, array_flip( $user_country_code_array ) );
return $intersect_countries;
}
add_filter( 'woocommerce_countries_allowed_countries', 'custom_update_allowed_countries', 30, 1 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With