How can I access the visitor’s country in JavaScript?

You can make the visitor’s location available in JavaScript by retrieving the geolocation data in PHP and passing it to a JavaScript variable.

Add the following code to your theme’s functions.php file:

add_action('wp_enqueue_scripts', function(){
    if(!defined('IFSO_PLUGIN_BASE_DIR')) return;
    require_once(IFSO_PLUGIN_BASE_DIR. 'services/geolocation-service/geolocation-service.class.php');
    $geo_data = \IfSo\Services\GeolocationService\GeolocationService::get_instance()->get_user_location();
    $ifso_country = !empty($geo_data->get('countryCode')) ? $geo_data->get('countryCode') : '';
    if(function_exists('wp_add_inline_script'))
        wp_add_inline_script('if-so',"var ifso_country = '{$ifso_country}';",'after');
});

This will expose the visitor’s country as a JavaScript variable named ifso_country, which you can use in your scripts.

You can adapt this approach to expose other geolocation values, such as city or state, by adjusting the data retrieved in the code.

Didn’t find what you need?