How to Get User Location by IP Address in WordPress

How to get a user’s location by IP address in WordPress

Geolocation lets you show or hide content depending on the visitor’s country: region-restricted products, localised promotions, country-specific notices. The approach has three steps: get the visitor’s IP, ask a geolocation service which country it belongs to, and act on the result.

Problem: Some content should be hidden from, or shown only to, customers from certain countries.

Step 1. Get the visitor’s IP address

function get_client_ip() {
    // Behind Cloudflare, the real visitor IP is in this header.
    // Only trust it if the site is actually behind Cloudflare.
    $headers = array( 'HTTP_CF_CONNECTING_IP', 'REMOTE_ADDR' );

    foreach ( $headers as $header ) {
        $ip = isset( $_SERVER[ $header ] ) ? trim( $_SERVER[ $header ] ) : '';

        if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) {
            return $ip;
        }
    }

    return '';
}

Headers like HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR are sent by the browser, so anyone can put any address there. Read them only if your server sits behind a proxy or load balancer that sets them, and then only the value added by that proxy. REMOTE_ADDR is the address of the actual connection and can’t be faked.

Step 2. Get the country from a geolocation service

The first version of this post used a free service over plain HTTP. That works, but requests and answers travel unencrypted, which is not acceptable on an HTTPS site. Services with HTTPS, such as ipgeolocation.io, usually allow about 1,000 requests per day on the free plan, so the result is cached per IP:

function get_client_country() {
    $ip = get_client_ip();

    if ( ! $ip || ! defined( 'IPGEO_API_KEY' ) ) {
        return '';
    }

    $transient = 'geo_country_' . md5( $ip );
    $cached    = get_transient( $transient );

    if ( false !== $cached ) {
        return $cached;
    }

    $url = add_query_arg( array(
        'apiKey' => IPGEO_API_KEY,
        'ip'     => $ip,
        'fields' => 'country_name',
    ), 'https://api.ipgeolocation.io/ipgeo' );

    $response = wp_remote_get( $url, array( 'timeout' => 3 ) );

    if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
        return '';
    }

    $data    = json_decode( wp_remote_retrieve_body( $response ), true );
    $country = isset( $data['country_name'] ) ? $data['country_name'] : '';

    set_transient( $transient, $country, DAY_IN_SECONDS );

    return $country;
}

Add your API key to wp-config.php:

define( 'IPGEO_API_KEY', 'your_api_key_here' );

Step 3. Use the country

For example, products with the ACF field show_for_usa are available only to visitors from the USA; everyone else is redirected to the home page:

add_action( 'template_redirect', 'redirect_hidden_posts' );
function redirect_hidden_posts() {
    if ( is_singular( 'product' ) && get_field( 'show_for_usa' ) ) {
        $country = get_client_country();

        // Unknown country (API error, local IP): let the visitor through.
        if ( $country && 'United States' !== $country ) {
            wp_safe_redirect( home_url( '/' ), 302 );
            exit;
        }
    }
}

A 302 (temporary) redirect is used because the same URL works for other visitors; a 301 would be cached by browsers and search engines.

Caching and accuracy

  • If the site uses page caching, the first visitor’s version of the page is served to everyone, and the redirect runs only for that first visitor. Exclude these pages from the page cache, or do the country check in JavaScript.
  • IP geolocation is not 100% accurate and is easy to bypass with a VPN. Use it for convenience, not as the only control where access restrictions are legally required.