Get user location

Problem: Hide or show some content for customers from different countries.

How get user location in WordPress?

Solution: At first we get customer IP, next get country by IP and then we can use country name for hide or show content.

Note: If you need hide custom post type and redirect user to other page, you can use last function redirect_hidden_posts().

function get_user_ip() {
	$ipaddress = '';
	if ( getenv( 'HTTP_CLIENT_IP' ) )
		$ipaddress = getenv( 'HTTP_CLIENT_IP' );
	else if ( getenv( 'HTTP_X_FORWARDED_FOR' ) )
		$ipaddress = getenv( 'HTTP_X_FORWARDED_FOR' );
	else if ( getenv( 'HTTP_X_FORWARDED' ) )
		$ipaddress = getenv( 'HTTP_X_FORWARDED' );
	else if ( getenv( 'HTTP_FORWARDED_FOR' ) )
		$ipaddress = getenv( 'HTTP_FORWARDED_FOR' );
	else if ( getenv( 'HTTP_FORWARDED' ) )
		$ipaddress = getenv( 'HTTP_FORWARDED' );
	else if ( getenv( 'REMOTE_ADDR' ) )
		$ipaddress = getenv( 'REMOTE_ADDR' );
	else
		$ipaddress = 'UNKNOWN';
		return $ipaddress;
}

function get_user_ip_details( $url ) {
	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
	$data = curl_exec( $ch );
	curl_close( $ch );
	
	return $data;
}
	
function get_user_country() {
	$myip = get_user_ip();
	$url = 'http://www.geoplugin.net/json.gp?ip=' . $myip;
	$details = ip_details( $url );
	$details_decode = json_decode( $details );
	$mycountry = $details_decode->geoplugin_countryName;
		
	return $mycountry;
}
	
add_action( 'template_redirect', 'redirect_hidden_posts' );
	
function redirect_hidden_posts() {
	if ( is_singular( 'product' ) ) {
		if ( get_field( 'show_for_usa' ) ) {
			if ( get_client_country() != 'United States' ) {
				wp_redirect( home_url() );
				exit;
			}
		}
		
	}
}

UPDATE

This way has one disadvantage - we work with the service, that use HTTP protocol and it's not good, especially if you use HTTPS on your website. Logical, that solutions for this trouble we could using services that use HTTPS. In general such services allow 1000 request per day in Free plan, our should just register and then use API of the service. For example, we can use this service (is not ad and you can using any service). After get API us should remake function get_user_country() change :

$url = 'http://www.geoplugin.net/json.gp?ip=' . $myip;

to

$url = 'https://api.ipgeolocation.io/ipgeo?apiKey=API_KEY&ip=' . $myip . '&fields=country_name';

Ultimately the function looks like this:

function get_client_country() {
	$myip = get_client_ip();
	$url = 'https://api.ipgeolocation.io/ipgeo?apiKey=API_KEY&ip=' . $myip . '&fields=country_name';
	$details = ip_details( $url );
	$details_decode = json_decode( $details );
	$mycountry = $details_decode->country_name;
		
	return $mycountry;
}

Leave Comment

Your email address will not be published. Required fields are marked *