WordPress Integration
This guide shows you how to integrate IPBot into your WordPress site for geolocation, security, and personalization features.
Overview
Section titled “Overview”WordPress doesn’t include built-in IP intelligence features. By integrating IPBot, you can:
- Block or redirect visitors from specific countries
- Detect and block proxy/VPN traffic
- Customize content based on visitor location
- Add security layers to login forms
- Track visitor analytics by region
Integration Methods
Section titled “Integration Methods”Method 1: Simple PHP Integration
Section titled “Method 1: Simple PHP Integration”Add this code to your theme’s functions.php file or create a custom plugin:
<?php/** * IPBot Integration for WordPress * Add to functions.php or create as a plugin */
// Get IP info from IPBot with cachingfunction get_ipbot_info($ip = null) { // Use client IP if none provided if (!$ip) { $ip = $_SERVER['REMOTE_ADDR']; }
// Check cache first (24 hours) $cache_key = 'ipbot_' . md5($ip); $cached = get_transient($cache_key); if ($cached !== false) { return $cached; }
// Call IPBot API $response = wp_remote_get('https://api.ipbot.com/' . $ip);
if (is_wp_error($response)) { return null; }
$body = wp_remote_retrieve_body($response); $data = json_decode($body, true);
// Cache for 24 hours set_transient($cache_key, $data, DAY_IN_SECONDS);
return $data;}
// Example: Country-based redirectfunction ipbot_country_redirect() { $info = get_ipbot_info();
if (!$info || isset($info['error'])) { return; }
$country = $info['location']['country_code'] ?? ''; $current_url = home_url($_SERVER['REQUEST_URI']);
// Redirect EU visitors to privacy page (except for the privacy page itself) if (in_array($country, ['DE', 'FR', 'IT', 'ES', 'NL']) && !strpos($current_url, '/privacy')) { wp_redirect(home_url('/privacy/')); exit; }}add_action('template_redirect', 'ipbot_country_redirect');
// Example: Block high-risk IPsfunction ipbot_block_high_risk() { $info = get_ipbot_info();
if (!$info || isset($info['error'])) { return; }
$risk_score = $info['security']['risk_score'] ?? 0;
// Block if risk score is high if ($risk_score > 70) { wp_die( 'Access denied. Your IP has been flagged as high-risk.', 'Access Denied', array('response' => 403) ); }}add_action('init', 'ipbot_block_high_risk');
// Example: Add country to admin user listfunction ipbot_add_country_column($columns) { $columns['country'] = 'Country'; return $columns;}add_filter('manage_users_columns', 'ipbot_add_country_column');
function ipbot_show_country_column($output, $column_id, $user_id) { if ($column_id === 'country') { // Get last known IP from user meta $last_ip = get_user_meta($user_id, 'last_login_ip', true); if ($last_ip) { $info = get_ipbot_info($last_ip); if ($info && !isset($info['error'])) { return esc_html($info['location']['country_code'] ?? 'Unknown'); } } return 'Unknown'; } return $output;}add_filter('manage_users_custom_column', 'ipbot_show_country_column', 10, 3);
// Example: Track user login IPfunction ipbot_track_login_ip($user_login, $user) { $ip = $_SERVER['REMOTE_ADDR']; update_user_meta($user->ID, 'last_login_ip', $ip); update_user_meta($user->ID, 'last_login_time', current_time('mysql'));}add_action('wp_login', 'ipbot_track_login_ip', 10, 2);
// Example: Show country-specific content shortcodefunction ipbot_country_shortcode($atts, $content = '') { $atts = shortcode_atts(array( 'countries' => '', // Comma-separated list of country codes 'show' => 'true' // Show or hide for these countries ), $atts);
$info = get_ipbot_info(); if (!$info || isset($info['error'])) { return ''; }
$user_country = $info['location']['country_code'] ?? ''; $allowed_countries = array_map('strtoupper', array_map('trim', explode(',', $atts['countries'])));
$should_show = in_array($user_country, $allowed_countries);
if ($atts['show'] === 'false') { $should_show = !$should_show; }
return $should_show ? do_shortcode($content) : '';}add_shortcode('country_content', 'ipbot_country_shortcode');Usage Examples
Section titled “Usage Examples”Country-Specific Content
Section titled “Country-Specific Content”[country_content countries="US,CA,GB"]<p>This content only shows to visitors from US, Canada, and UK.</p>[/country_content]
[country_content countries="CN,RU" show="false"]<p>This content is hidden for visitors from China and Russia.</p>[/country_content]Method 2: Complete Plugin
Section titled “Method 2: Complete Plugin”For a more robust solution, create a dedicated plugin file:
<?php/** * Plugin Name: IPBot Integration * Description: Integrate IPBot IP intelligence into WordPress * Version: 1.0.0 * Author: Your Name */
// Prevent direct accessif (!defined('ABSPATH')) { exit;}
class IPBot_WordPress { private $api_url = 'https://api.ipbot.com/'; private $cache_time = DAY_IN_SECONDS;
public function __construct() { add_action('admin_menu', array($this, 'add_admin_menu')); add_action('admin_init', array($this, 'register_settings')); }
public function get_ip_info($ip = null) { if (!$ip) { $ip = $this->get_client_ip(); }
$cache_key = 'ipbot_' . md5($ip); $cached = get_transient($cache_key);
if ($cached !== false) { return $cached; }
$response = wp_remote_get($this->api_url . $ip, array( 'timeout' => 5, 'headers' => array( 'Accept' => 'application/json' ) ));
if (is_wp_error($response)) { return array('error' => 'API request failed'); }
$data = json_decode(wp_remote_retrieve_body($response), true); set_transient($cache_key, $data, $this->cache_time);
return $data; }
private function get_client_ip() { $ip = '';
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) { $ip = $_SERVER['HTTP_CF_CONNECTING_IP']; } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]; } elseif (isset($_SERVER['HTTP_X_REAL_IP'])) { $ip = $_SERVER['HTTP_X_REAL_IP']; } else { $ip = $_SERVER['REMOTE_ADDR']; }
return sanitize_text_field($ip); }
public function add_admin_menu() { add_options_page( 'IPBot Settings', 'IPBot', 'manage_options', 'ipbot-settings', array($this, 'settings_page') ); }
public function register_settings() { register_setting('ipbot_settings', 'ipbot_cache_time'); register_setting('ipbot_settings', 'ipbot_blocked_countries'); register_setting('ipbot_settings', 'ipbot_block_proxies'); register_setting('ipbot_settings', 'ipbot_min_risk_score'); }
public function settings_page() { ?> <div class="wrap"> <h1>IPBot Settings</h1> <form method="post" action="options.php"> <?php settings_fields('ipbot_settings'); do_settings_sections('ipbot_settings'); ?> <table class="form-table"> <tr> <th scope="row">Cache Time (seconds)</th> <td> <input type="number" name="ipbot_cache_time" value="<?php echo esc_attr(get_option('ipbot_cache_time', DAY_IN_SECONDS)); ?>"> <p class="description">How long to cache IP responses (default: 86400 = 24 hours)</p> </td> </tr> <tr> <th scope="row">Blocked Countries</th> <td> <input type="text" name="ipbot_blocked_countries" value="<?php echo esc_attr(get_option('ipbot_blocked_countries', '')); ?>"> <p class="description">Comma-separated country codes (e.g., CN,RU)</p> </td> </tr> <tr> <th scope="row">Block Proxies/VPNs</th> <td> <input type="checkbox" name="ipbot_block_proxies" value="1" <?php checked(get_option('ipbot_block_proxies', 0)); ?>> <p class="description">Block visitors using proxies or VPNs</p> </td> </tr> <tr> <th scope="row">Minimum Risk Score to Block</th> <td> <input type="number" name="ipbot_min_risk_score" min="0" max="100" value="<?php echo esc_attr(get_option('ipbot_min_risk_score', 70)); ?>"> <p class="description">Block visitors with risk score above this value (0-100)</p> </td> </tr> </table> <?php submit_button(); ?> </form> </div> <?php }}
// Initialize the pluginnew IPBot_WordPress();
// Helper function for themesfunction ipbot_get_info($ip = null) { global $ipbot_wp; if (!$ipbot_wp) { $ipbot_wp = new IPBot_WordPress(); } return $ipbot_wp->get_ip_info($ip);}Security Best Practices
Section titled “Security Best Practices”When using IPBot in WordPress, follow these security practices:
1. Always Cache Responses
Section titled “1. Always Cache Responses”// Cache for appropriate time based on use caseset_transient($cache_key, $data, DAY_IN_SECONDS); // Residential IPsset_transient($cache_key, $data, HOUR_IN_SECONDS); // Datacenter IPs2. Sanitize All Data
Section titled “2. Sanitize All Data”$country = sanitize_text_field($info['location']['country'] ?? '');$risk_score = intval($info['security']['risk_score'] ?? 0);3. Use Nonces for Forms
Section titled “3. Use Nonces for Forms”wp_nonce_field('ipbot_action', 'ipbot_nonce');4. Check Permissions
Section titled “4. Check Permissions”if (!current_user_can('manage_options')) { return;}Testing Your Integration
Section titled “Testing Your Integration”Add a test page to verify IPBot is working:
// Add to functions.php or your pluginfunction ipbot_test_page() { if (!isset($_GET['ipbot_test'])) { return; }
if (!current_user_can('manage_options')) { return; }
$info = ipbot_get_info(); echo '<pre>' . esc_html(print_r($info, true)) . '</pre>'; exit;}add_action('init', 'ipbot_test_page');Visit yoursite.com/?ipbot_test=1 while logged in as admin to see the raw API response.
Troubleshooting
Section titled “Troubleshooting”Issue: API requests timing out
Section titled “Issue: API requests timing out”Solution: Increase the timeout or implement fallback behavior:
$response = wp_remote_get($url, array('timeout' => 10));Issue: Cache not clearing
Section titled “Issue: Cache not clearing”Solution: Clear transients when needed:
delete_transient('ipbot_' . md5($ip));Issue: Incorrect IP detection
Section titled “Issue: Incorrect IP detection”Solution: Handle proxy headers properly:
// Check various proxy headers$headers_to_check = [ 'HTTP_CF_CONNECTING_IP', // Cloudflare 'HTTP_X_FORWARDED_FOR', // General proxy 'HTTP_X_REAL_IP', // Nginx 'REMOTE_ADDR' // Direct connection];