I am working on WooCommerce checkout page. I can set default country using filter in functions.php file for all users. That’s fine.
But I need to set country name in checkout page based on location for both logged in and logged out users. For an example, If a user from USA, the user will see USA is selected in the country dropdown list in checkout page. And If user form Canada, the user will see Canada is selected the country dropdown list in checkout page.
2
Answers
you set to change the default country with this code.
Steps to be done before you insert this code can:
1- Install this plugin:
https://wordpress.org/plugins/geoip-detect/
2- Activate the GeoIP API (data sources): the service that will return the location for you. You cand o this inside the plugin settings.
3- Insert this code into function.php:
!!!! The code will not work without the plugin because it’s using a shortcode made by that plugin.
But remember that this is for any user who doesn’t have a saved billing address because Woocommerce will consider it on the default country.
As Woocommerce already includes a geolocation IP via
WC_Geolocation
Class, that will allow you to get and set user geolocated country as default checkout country. There is no need of any additional plugin.The code that will set by default the geolocated IP user country in checkout:
If you want to do the same for checkout State field, you will use additionally the following:
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Related: