Tayyab Vohra
Tayyab Vohra

Reputation: 1662

how to fetch user location in wordpress

I am trying to show the user region and country from IP address but I am not been able to get it. Every time when I am passing the IP address to different API I am getting please enter the valid IP address. I am doing this using shortcode inside the functions.php and I am accessing the shortcode in the footer.php but it is not working.

This is the code which I have write in functions.php

function user_region() { 
       $ip = "27.255.58.21";
       $http = wp_remote_get( 'https://ipinfo.io/{$ip}/json' );
       $data = wp_remote_retrieve_body( $http );
       $result=print_r($data);


  return '<div class="user-region">'.$data->country_name.'</div>';  

    }  

add_shortcode("get-user-region", "user_region"); 

this is what i am getting in the footer

enter image description here

Upvotes: 1

Views: 1023

Answers (1)

BugHunterUK
BugHunterUK

Reputation: 8948

You're attempting to use variable interpolation using single quotes. That will not work. Replace the single quotes with double quotes. Using double quotes allows for variable expansion, but single quotes doesn't.

Try this:

$http = wp_remote_get("https://ipinfo.io/{$ip}/json");

Or, if you insist on using single quotes:

$http = wp_remote_get('https://ipinfo.io/' . $ip . '/json');

Upvotes: 1

Related Questions