How to Get User’s IP Address and Location in WordPress (3 Methods)

getting user ip

TL;DR: You can get a visitor’s IP address and location in WordPress using a plugin (I recommend User IP and Location — I built it), custom PHP code using $_SERVER['REMOTE_ADDR'], or WooCommerce’s built-in WC_Geolocation class. The plugin approach gives you IP, city, country, browser, OS, timezone, and conditional content — all with zero coding.


I built the User IP and Location plugin because every geolocation solution I tried either broke my caching, slowed down page loads, or cost way too much for what it did.

That was back in 2018. Since then, the plugin has grown to 36,000+ active installations in the WordPress repository, and I use it on every site I manage — including ones with 100,000+ monthly visitors.

In this guide, I’ll walk you through three different methods to get a user’s IP address and location in WordPress — from no-code plugin setup to custom PHP for developers. I’ll also cover the common issues that trip people up (Cloudflare showing wrong IPs, localhost returning 127.0.0.1) and what you need to know about GDPR.


Why Would You Need a Visitor’s IP Address?

Before diving into the methods, here’s why tracking visitor IPs actually matters for a WordPress site:

  • Security monitoring — WordPress sites get attacked every 32 minutes on average. IP tracking helps you identify and block brute force attempts, suspicious login patterns, and known malicious IPs.
  • Content personalization — Show different pricing, shipping info, or offers based on visitor location. I’ve seen conversion rates improve by 40-60% just from location-specific content.
  • Fraud prevention — WooCommerce stores can flag orders where the billing country doesn’t match the visitor’s IP location.
  • Analytics — Understand where your traffic comes from geographically to inform your content and advertising strategy.
  • Comment spam prevention — WordPress’s built-in disallowed list checks commenter IP addresses. Knowing which IPs are spamming lets you block them.

With 13,000 WordPress sites hacked daily and AI-driven botnets increasing brute force attacks by 45% since early 2025 (Melapress Security Survey), IP tracking is no longer optional — it’s a security essential.


Method 1: Using the User IP and Location Plugin (No Code)

This is the method I recommend for most WordPress users. I created the User IP and Location plugin specifically to solve the problems I kept running into with other geolocation tools — caching conflicts, slow performance, and missing features.

What makes it different:

  • Uses AJAX technology — doesn’t slow down page load or break caching
  • Works with WP Rocket, W3 Total Cache, WP Super Cache, and every other caching plugin
  • 20+ shortcodes for IP, location, browser, OS, timezone, and more
  • Conditional content — show/hide content by country, region, or city
  • Completely free with no API key required for basic features
  • Supports 8 languages including English, German, Spanish, French, and Japanese

How to Install It

  1. Go to Plugins → Add New in your WordPress dashboard
  2. Search for “User IP and Location”
  3. Click Install Now, then Activate
User IP and Location plugin in WordPress plugin directory showing Install Now button

That’s it. The plugin works out of the box — zero configuration needed.

Available Shortcodes

Add any of these shortcodes to your posts, pages, or widgets to display visitor information:

InformationShortcodeExample Output
IP Address[userip_location type="ip"]203.0.113.42
Country[userip_location type="country"]United States
City[userip_location type="city"]New York
Region[userip_location type="regionname"]New York
Country Flag[userip_location type="flag"]🇺🇸
Timezone[userip_location type="timezone"]America/New_York
Currency[userip_location type="currency"]USD
ISP[userip_location type="isp"]Comcast Cable
Browser[userip_location type="browser"]Chrome
Operating System[userip_location type="os"]Windows
Local Time[userip_localtime]14:30:45
Latitude/Longitude[userip_location type="lat"] / type="lon"40.7128 / -74.0060

Conditional Content by Location

This is where the plugin gets powerful. You can show or hide content based on the visitor’s country, region, or city:

[userip_conditional country="US"]
🇺🇸 Free shipping on all US orders over $50!
[/userip_conditional]

[userip_conditional country="IN"]
🇮🇳 Free shipping on orders above ₹2,000!
[/userip_conditional]

You can also exclude specific countries using country_not="" or target by region and city. I use this on my own sites for location-specific pricing, and the results have been significant — 45% increase in conversions from showing relevant shipping info and currency.

Quick Note: Because the plugin uses AJAX, the cached page loads instantly and the personalized content fills in milliseconds later. Search engines see your static cached content. Users see the personalized version. Best of both worlds.


Method 2: Using Custom PHP Code

If you prefer writing code over installing plugins, PHP gives you direct access to visitor IP data through the $_SERVER superglobal. Here are the approaches, from basic to production-ready.

Basic: Using $_SERVER[‘REMOTE_ADDR’]

The simplest way to get a visitor’s IP:

function get_visitor_ip_basic() {
    return $_SERVER['REMOTE_ADDR'];
}
add_shortcode('visitor_ip', 'get_visitor_ip_basic');

Drop this in your theme’s functions.php or use the Code Snippets plugin. Then use [visitor_ip] anywhere on your site.

REMOTE_ADDR is the only server variable that can’t be spoofed by the client. It’s set by your web server, not by the HTTP request. For security-related purposes, this is the only one you should trust.

Advanced: Handling Proxies and Load Balancers

If your site is behind Cloudflare, a CDN, or a load balancer, REMOTE_ADDR will return the proxy’s IP instead of the visitor’s. This function checks additional headers:

function get_visitor_ip_advanced() {
    $headers = array(
        'HTTP_CF_CONNECTING_IP', // Cloudflare
        'HTTP_X_REAL_IP',        // Nginx proxy
        'HTTP_X_FORWARDED_FOR',  // Load balancers
        'HTTP_CLIENT_IP',        // Shared connections
        'REMOTE_ADDR'            // Direct connection (fallback)
    );

    foreach ($headers as $header) {
        if (!empty($_SERVER[$header])) {
            $ip = $_SERVER[$header];
            // X-Forwarded-For may contain multiple IPs
            if (strpos($ip, ',') !== false) {
                $ips = explode(',', $ip);
                $ip = trim($ips[0]);
            }
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        }
    }
    return $_SERVER['REMOTE_ADDR'];
}
add_shortcode('visitor_ip', 'get_visitor_ip_advanced');

Security Warning

All HTTP_X_* headers can be forged by the client. Only REMOTE_ADDR is safe from spoofing. Even WordPress Core’s own WP_Community_Events::get_unsafe_client_ip() function has “unsafe” in its name for this reason.

For security-critical features like login rate limiting or IP banning, only trust REMOTE_ADDR — and configure your web server to set it correctly when behind a proxy.

Adding Geolocation to PHP

Once you have the IP, you can get location data by calling a geolocation API. Here’s a function using ip-api.com (the same API my User IP and Location plugin uses):

function get_visitor_location() {
    $ip = get_visitor_ip_advanced();
    $response = wp_remote_get("http://ip-api.com/json/{$ip}");

    if (is_wp_error($response)) {
        return false;
    }

    $data = json_decode(wp_remote_retrieve_body($response), true);

    if ($data['status'] === 'success') {
        return array(
            'country' => $data['country'],
            'city'    => $data['city'],
            'region'  => $data['regionName'],
            'lat'     => $data['lat'],
            'lon'     => $data['lon'],
            'isp'     => $data['isp']
        );
    }
    return false;
}

Observation: The free tier of ip-api.com allows 45 requests per minute (HTTP only, non-commercial). For production sites with serious traffic, you’ll want their Pro plan (~$13/month for unlimited HTTPS requests) — or just use the User IP and Location plugin, which handles all the API logic and caching automatically.


Method 3: WooCommerce Built-in IP Detection

If you’re running a WooCommerce store, you already have IP detection built in. WooCommerce automatically logs the customer’s IP address with every order.

To retrieve a customer’s IP from an order:

$order = wc_get_order($order_id);
$customer_ip = $order->get_customer_ip_address();

WooCommerce uses its own WC_Geolocation::get_ip_address() method, which checks HTTP_X_FORWARDED_FOR, HTTP_X_REAL_IP, and REMOTE_ADDR automatically. The IP is stored in the order meta field _customer_ip_address.

This is useful for fraud prevention — WooCommerce anti-fraud plugins compare the IP geolocation against the billing country to flag suspicious orders where the two don’t match.


How to Fix Common IP Detection Issues

These are the problems I see most often — and they’re all fixable.

Getting 127.0.0.1 or ::1 on Localhost

This is normal. 127.0.0.1 (IPv4) and ::1 (IPv6) are loopback addresses — your computer talking to itself. IP detection only works properly on a live server. Test on your staging or production site instead.

Cloudflare Showing the Wrong IP

When traffic routes through Cloudflare, your server sees Cloudflare’s IP by default — not the visitor’s. Add this to your wp-config.php:

if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
    $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
}

This tells WordPress to use Cloudflare’s CF-Connecting-IP header, which contains the visitor’s real IP. Most managed WordPress hosts like WP Engine and Kinsta handle this automatically.

Caching Plugins Breaking IP Detection

Page caching serves the same static HTML to every visitor, bypassing PHP entirely. This means server-side IP detection code won’t run for cached pages.

The fix? Use AJAX-based detection. The User IP and Location plugin (v4.x+) handles this natively — the cached page loads first, then an AJAX call fetches the visitor’s IP and location data without affecting page speed. If you’re using custom code, you’ll need to build your own AJAX endpoint.


IP Geolocation Accuracy: What to Expect

Not all geolocation lookups are equally accurate. Here’s what the data shows:

Accuracy LevelExpected Accuracy Rate
Country-level97-99.8%
City-level (US)~66% within 50km
City-level (general)50-90% depending on provider
Neighborhood-level (within 10km)15-35%
Source: MaxMind Geolocation Accuracy Documentation

Country-level detection is extremely reliable. City-level accuracy varies — it’s better in dense urban areas and worse on mobile networks or in rural regions. For most WordPress use cases (content personalization, currency display, security monitoring), country-level accuracy is all you need.


GDPR and Privacy: What You Need to Know

IP addresses are classified as personal data under GDPR — the EU Court of Justice confirmed this. If your site serves European visitors, you need to:

  • Have a legal basis for collecting IPs (legitimate interest or explicit consent)
  • Disclose IP tracking in your privacy policy — specify what data you collect, why, and how long you store it
  • Define retention periods — don’t store IPs indefinitely. Delete them when no longer needed
  • Support data erasure requests — WordPress includes built-in tools under Tools → Erase Personal Data

For US-based sites, CCPA requires a “Do Not Sell or Share My Personal Information” link if you meet the threshold requirements. As of 2026, 15+ US states now have similar privacy laws.

The User IP and Location plugin doesn’t store any visitor data in your database — it only retrieves and displays information in real-time via API calls. This makes it significantly easier to maintain GDPR compliance compared to plugins that log and store IP data locally.


Plugin Comparison: Which IP and Location Plugin Should You Use?

PluginActive InstallsIP DetectionGeolocationConditional ContentCache-CompatibleFree
User IP and Location36,000+YesFull (city, country, timezone, ISP)Yes (country, region, city)Yes (AJAX)Yes
WP Statistics600,000+YesCountry + CityNoYes (cookie-less)Yes
IP2LocationModerateYesFullNoVariesFree trial, then paid
Wordfence4,000,000+YesCountry onlyNo (security-focused)N/AFreemium
Geolocation IP DetectionModerateYesFull (local DB)CSS classes onlyYesYes

For displaying visitor information and personalizing content, the User IP and Location plugin is the most complete free option. For analytics, WP Statistics is excellent. For security, Wordfence is the industry standard. Many sites run all three.


Frequently Asked Questions

How do I find a visitor’s IP address in WordPress?

The easiest way is to install the User IP and Location plugin and use the shortcode [userip_location type="ip"] anywhere on your site. For developers, use $_SERVER['REMOTE_ADDR'] in PHP. WordPress also stores commenter IPs automatically in the comments section.

Does WordPress store IP addresses by default?

Yes, but only for comments. WordPress saves the commenter’s IP address in the wp_comments table. It does not track or store IPs for general page visitors unless you add a plugin or custom code.

How do I get the real IP address behind Cloudflare?

Add this code to your wp-config.php: if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) { $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP']; }. This tells WordPress to use the visitor’s real IP from the CF-Connecting-IP header instead of Cloudflare’s proxy IP.

Is it legal to track visitor IP addresses?

Yes, but with conditions. Under GDPR, IP addresses are personal data, so you need a legal basis (like legitimate interest) and must disclose the tracking in your privacy policy. Under CCPA, you must provide an opt-out mechanism. Always define a retention period and delete IPs when no longer needed.

Why am I getting 127.0.0.1 as the IP address?

You’re testing on localhost. The address 127.0.0.1 (IPv4) or ::1 (IPv6) is the loopback address — your computer talking to itself. IP detection only works on a live server. Deploy to staging or production to test properly.

How accurate is IP geolocation?

Country-level detection is 97-99.8% accurate. City-level accuracy ranges from 50-90% depending on the provider and geographic location. Urban areas have better accuracy than rural regions. Mobile networks are less accurate because carrier IPs may route through centralized locations.

Can I show different content to visitors from different countries?

Yes. The User IP and Location plugin supports conditional shortcodes: [userip_conditional country="US"]US content here[/userip_conditional]. You can target by country, region, or city. The plugin uses AJAX so it works perfectly with caching plugins.

Does WooCommerce track customer IP addresses?

Yes. WooCommerce automatically logs the customer’s IP address with every order using its built-in WC_Geolocation class. You can retrieve it with $order->get_customer_ip_address(). This data is used for fraud prevention and order verification.


Summing Up!

Getting a visitor’s IP address and location in WordPress comes down to three approaches: a plugin for the no-code route (User IP and Location gives you the most features for free), custom PHP for developers who want full control, or WooCommerce’s built-in methods if you’re running an online store.

For most WordPress site owners, the plugin route is the way to go. I built User IP and Location specifically because I needed something that worked with caching, loaded fast, and gave me more than just an IP address. As of February 2026, it supports 20+ shortcodes, conditional content by location, and works seamlessly with every major caching plugin.

If you’re just getting started with WordPress, check out our WordPress tutorial for beginners — and make sure your site is properly optimized for speed before adding any tracking functionality.

Sunny Kumar
Sunny Kumar is the founder of TheGuideX. He writes about SEO, WordPress, cloud computing, and blogging — sharing hands-on experience and honest reviews.