David Stockdale's Scrapcode

Get Country Name From IP

Today I had the idea of compiling an automatic list of how many spam comments I get from the same country.

After a bit of research I have begun by finding out how to get country names from an IP address.

This is the code I used:

 * Adds Location Finder shortcode.
add_shortcode('location_finder', 'location_finder_shortcode');
 * Checks the country of the IP address.
 * ip: [location_finder ip=""]
function location_finder_shortcode($atts) {
	$result = "N/A";

	$ip_address = $atts['ip'];
	$geopluginURL = 'http://www.geoplugin.net/php.gp?ip=' . $ip_address;

	$geoip_response = unserialize( file_get_contents( $geopluginURL ) );

	if ( ! empty( $geoip_response ) ) {
		$result = $geoip_response['geoplugin_countryName'];
	return $result;

This uses the GeoPlugin service (requires no sign up or actual plugin, the code above can simply be pasted into function.php).

Leave a Reply