I want to limit the Countries in the Shippiment to another address and Billing (Checkout) to the User IP Address location. Say the user is in USA I only want this country to show as a option under the dropdown country list or disable the option of changing the country. How would I do that? Thanks in advance.
1 Answer
First of all to make geolocation work properly go to WooCommerce > Status and check MaxMind GeoIP database
option, if there is red checkmark follow the provided instructions to download the database.
Then you can add this code to your theme (at the bottom of functions.php
) or add it as a plugin or code snippet as changes in theme might get lost when you update it.
function wpse_287199_woo_checkout_country( $fields ) {
$geoData = WC_Geolocation::geolocate_ip();
$countries = WC()->countries->get_countries();
$fields['billing']['billing_country'] = array(
'type' => 'select',
'label' => __('Country', 'woocommerce'),
'options' => array(
$geoData['country'] => $countries[$geoData['country']]
),
'class' => array(
'form-row-wide',
'address-field',
'update_totals_on_change'
)
);
$fields['shipping']['shipping_country'] = array(
'type' => 'select',
'label' => __('Country', 'woocommerce'),
'options' => array(
$geoData['country'] => $countries[$geoData['country']]
),
'class' => array(
'form-row-wide',
'address-field',
'update_totals_on_change'
)
);
return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'wpse_287199_woo_checkout_country' );
This code checks the client’s IP geolocation and determines his country then it is used for shipping and billing as an only option.