DEAL ENDS IN:

SUMMER SALE!

UP TO 35% OFF!

GET IT NOW

Is there a way to capture the user’s country in JavaScript?

Yes, you can capture the user’s country in JavaScript by using the following PHP code in your theme’s functions.php file. This code fetches the user’s geolocation data and sets it as a JavaScript variable:

phpCopy codeadd_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 code will make the user’s country available as a variable named ifso_country in your JavaScript. You can customize this code to capture other geolocation data, such as city or state, by adjusting the values in the code.