WP.com Geo Uniques

Target distinct markets with different content by geo-targetting users at a country level, while still benefitting from the awesomeness that is Batcache.

Target distinct markets with different content while still benefitting from the awesomeness that is Batcache.

Usage: Simple Mode

wpcom_vip_load_plugin( 'wpcom-geo-uniques' );
wpcom_geo_add_location( 'us' ); // add list of supported countries

if ( 'us' == wpcom_geo_get_user_location() ) {
    echo "USA: A-Okay!";
} else {
    echo "You're not American! No soup for you!";
}

Usage: Advanced Mode

By default, geo-location happens at a country-level but this can be extended to cities and states in advanced mode. This requires

It requires three pieces:

  • enabling advanced mode
  • defining your location groups
  • writing some js that handles group assignment based on the user’s geolocation data

In your theme:

// Explicitly enable advanced mode
add_filter( 'wpcom_geo_simple_mode', '__return_false', 999 );

// Return the region value for use in the cache key
wpcom_geo_add_location( 'san-francisco' );
wpcom_geo_set_default_location( 'national' );

// This is the URL to the js file where we will handle our location assignment
add_filter( 'wpcom_geo_client_js_src', function( $url ) {
    return get_template_directory_uri() . '/js/geo.js';
} );

In the JS file:

wpcom_geo.set_detect_success_callback( function( geo_data ) {
    // Figure out the user's location based on the returned data.
    // geo_data is an object that includes:
    // - latitude
    // - longitude
    // - country_short
    // - country_long
    // - region
    // - city

    if ( 'SAN FRANCISCO' === geo_data.city ) {
        return 'san-francisco';
    }

    return false; // default

} );

wpcom_geo.set_detect_error_callback( function() {
    // TODO: handle error here; default location is already set.
} );

// Kicks things off;
wpcom_geo.detect();

This plugin relies on WP.com-specific functions to be fully functional but will work in your local environment with WP_DEBUG === true.

If you just need to know which country the user is visiting from, we have a variable $_SERVER['GEOIP_COUNTRY_CODE'] which is quicker than wpcom_geo_get_user_location(), but you’ll need to handle your own Batcache variants if you use this. Examples values are “US” (N. America), “RU” (Russia), or “GB” (Great Britain). This variable is set for all requests and does not require the WP.com Geo Uniques plugin to be active.

Note that either of these techniques should only be used with a very small list of countries for performance reasons.

Please get in touch before using this plugin.