I'd like to implement the ability to incorporate an API into my Wordpress blog that allows people to perform an IP lookup within my blog. So far all of my attempts have failed when incorporating the function to Wordpress. As a standalone code, it works just fine. The goal is to use a domain.com/ip/1.1.1.1 and my attempts either show a 404, redirect to home page, or just show most recent posts.
Here's what I have:
custom rewrite endpoint
function ip_info_rewrite_endpoint() {
add_rewrite_endpoint('ip', EP_ROOT);
}
add_action('init', 'ip_info_rewrite_endpoint');
functions.php
function ip_info_shortcode() {
global $wp_query;
$ip = $wp_query->get('ip');
if (!$ip) {
return "<h1>Please provide an IP address</h1>";
}
$url = "http://ip-api.com/php/{$ip}?fields=status,message,continent,country,countryCode,region,regionName,city,district,zip,lat,lon,timezone,isp,org,as,asname,reverse,proxy,hosting,query";
$response = file_get_contents($url);
$data = unserialize($response);
if ($data['status'] == 'fail') {
return "<h1>IP Information Not Found</h1>";
} else {
$output = "<h1>IP Information for {$data['query']}</h1>";
$output .= "<table>";
$output .= "<tr><th>IP Address</th><td>{$data['query']}</td></tr>";
$output .= "<tr><th>Continent</th><td>{$data['continent']}</td></tr>";
$output .= "<tr><th>Country</th><td>{$data['country']}</td></tr>";
$output .= "<tr><th>Region</th><td>{$data['regionName']}</td></tr>";
$output .= "<tr><th>City</th><td>{$data['city']}</td></tr>";
$output .= "<tr><th>ZIP Code</th><td>{$data['zip']}</td></tr>";
$output .= "<tr><th>Latitude</th><td>{$data['lat']}</td></tr>";
$output .= "<tr><th>Longitude</th><td>{$data['lon']}</td></tr>";
$output .= "<tr><th>Time Zone</th><td>{$data['timezone']}</td></tr>";
$output .= "<tr><th>ISP</th><td>{$data['isp']}</td></tr>";
$output .= "</table>";
return $output;
}
}
add_shortcode('ip_info', 'ip_info_shortcode');
RewriteRule ^ip/([0-9\.]+)/?$ /index.php?page_id=2529 [L,QSA]