Simple way to get location from IP address using PHP, get country name and code by visitor IP in PHP & WordPress, tutorial & example.

Live Demo

Your country name is "United States" and country code is "US".

How To Get Location From IP Using PHP

Using GeoPlugin API and some PHP functions, we will get location from IP address, we will get country name and country code.

Get Location From IP In PHP

Use this code:

    /* Code by Qassim Hassan, */

    $user_ip = $_SERVER['REMOTE_ADDR'];
    $result = unserialize( file_get_contents("$user_ip") );

    if( !empty($result['geoplugin_countryCode']) ){
        $country_code = $result['geoplugin_countryCode'];
        $country_code = 'Unknown';

    if( !empty($result['geoplugin_countryName']) ){
        $country_name = $result['geoplugin_countryName'];
        $country_name = 'Unknown';

    echo 'Your country name is ' . $country_name;

    echo '

    echo 'Your country code is ' . $country_code;


Get Location By IP In WordPress

Copy function code and paste it in your functions.php file:

function WPTime_get_location_by_ip_address($ip = null){
    /* Function by Qassim Hassan, */

    if( empty($ip) ){
        $user_ip = $_SERVER['REMOTE_ADDR'];
        $user_ip = $ip;

    $api = "$user_ip";
    $get = wp_remote_get($api);
    $result = unserialize( wp_remote_retrieve_body($get) );

    if( empty($result['geoplugin_countryName']) ){
        $country_name = "Unknown"; // if country name is empty
        $country_name = $result['geoplugin_countryName']; // user country name!

    if( empty($result['geoplugin_countryCode']) ){
        $country_code = "Unknown"; // if country code is empty
        $country_code = $result['geoplugin_countryCode']; // user country code!

    return '

Your country name is "'.$country_name.'" and country code is "'.$country_code.'".

add_shortcode('user_location', 'WPTime_get_location_by_ip_address');

Now use this shortcode [user_location] in your post to display user country name and country code, you can use it in custom place, just call function like this:

<?php echo WPTime_get_location_by_ip_address($_SERVER['REMOTE_ADDR']); // get location by user ip echo WPTime_get_location_by_ip_address('enter ip address here'); // get location by any ip ?>