Geotargeting WordPress plugin hide or show widget for specific countries. Guide to Implementing Geotargeting on WordPress


Geotargeting to geolocate users depending on their country of residence. The plugin is ideal for affiliate sites such as online casinos, where you need to sort visitors depending on the country or city visited, for commerce sites, where visitors need to display different products depending on the country. There is also a free version of the plugin for WordPress. Geotargeting is compatible with GeoIP2 databases and has API services to display the most accurate data. Main advantages of the plugin:

Creation of regions. You can group countries and cities in a custom order to make it easier for users to select. For example, you can create a region called Europe and another called America, and then use these names in shortcodes.

Shortcode generator. With help powerful generator shortcodes you can show various information depending on the country or region.

Support for many services. The plugin is based on a free database, but Maxmind API premium is also supported, so you can use online api with this plugin. The user's IP is automatically calculated, regardless of the service (Cloudflare, Sucuri, Akamai, Ezoic or Reblaze)

Widgets. Not only can you display different content, but after activating the plugin you can display different widgets.

Redirect users based on country, region, or city. Create as many redirects as you need, sending users to the relevant website. This is a great feature for large companies that create separate websites for each country, or for websites ecommerce, which sell different goods in individual cities.

Targeting inWordPress menu. You can show or hide individual menu items to users using the appropriate options.

ModulesVisual Composer. The Geotargeting plugin fully supports Visual Composer from WPBakery by adding 3 modules where you can select any elements for geotargeting.

Compatible with cache plugins. The disadvantage of geotargeting is problems with page cache. By enabling AJAX, all filters, shortcodes, and geotargeting options will be loaded after the page is unloaded from cache. You'll get cache loading speeds and geo-targeting benefits. Compatible with WP-Super Cache,W3 Total cache, Wp Rocket and other plugins.

WooCommerce and light e-commerce. Now you can easily hide products depending on the country or city of the visitor. You can either hide the product completely or display a message indicating that it is not available in your region.

Easy for developers. The plugin uses a powerful PHP API, geotargeting of content occurs directly on the template. Compatible with the Advanced Custom Fields plugin. The code is clean and well organized, with markups and filters.

Geotargeting is the provision of specific content to website visitors based on their geographic location, usually a country or city, identified by their IP address.

This technique has been around for so long that it has become ubiquitous. Google provides search results tailored to your location, Amazon offers personalized home pages with recommended products, and eBay displays local currency.

A more recent example of geotargeting is WordPress itself. The current 4.8 release includes a new dashboard widget that displays upcoming events tailored to your geographic location:

Using Google Analytics to Determine Visitor Locations

you can use Google Analytics to learn more about your visitors and where they are from. To do this, log into the analytical service and go to the tab Audience > Demographics > Geo > Location:

You'll see a color-coded map of the world that matches your audience demographics. A little lower - more detailed analysis, including countries where users are located, sessions, new users, bounce rate, transactions and revenue.

You can use this information to personalize content on your site. For example, based on the geodata in the above Google profile Analytics, you can:

  • Add a German translation to the site;
  • Allocate more time to promoting content to American audiences ( for example, organize promotions for weekends in the USA);
  • Inform German visitors that you are collecting their information in accordance with EU cookie law;
  • Connect with visitors by greeting them in a location-appropriate manner ( for example, say “G"Day!” to Australian visitors);
  • Showcase customer reviews from the same geographic area as the user;
  • Let visitors from the US, Canada, Australia, UK and Germany know that you are delivering to their location.

Using Geotargeting in WordPress

Let's look at a simple example of using geotargeting for a website: displaying welcome messages to visitors from different countries.

Display a welcome message

Let's assume that you have launched an online store specializing in selling hats. Your caps are selling out quickly thanks to the summer heat. But there is still a stock of winter hats that are collecting dust in the warehouse. Luckily, winter in Australia is the perfect opportunity to attract customers in the southern hemisphere and clear out inventory.

In this example I want to show an alternative greeting on my home page, which is only shown to visitors from Australia. Visitors from other countries will see a standard welcome message.

Step 1: Install plugins

To implement this example, we will use several free plugins available in the WordPress Plugin Directory:

  • Custom Content by Country ;
  • Widgets on Pages ;
  • Shortcode Widget.

Custom Content by Country is a simple plugin that uses shortcodes to display content based on users' location. We will use it to geotarget content. Let's start by using it to display an alternative greeting.

I want to display an alternative welcome message above the theme header, so I use the Widgets on Pages plugin to add a widget to the header.

The Shortcode Widget plugin makes it easy to use shortcodes on your site, without having to add a filter to your functions.php file or create a child theme.

Step 2: Create a custom widget

In this example geotargeting WordPress I use the popular free theme Zerif Lite. Here's what it looks like right after installation:

I want to display a custom greeting instead of the generic one included in the Zerif Lite theme. To do this I will use my own widget.

First, let's make a few changes to the theme we're using:

  • Replace the header image;
  • Remove the green button;
  • Let's replace the text of the red button.

Now let's create our own header widget using Widgets on Pages. Go to the tab Widgets on Pages > Turbo Sidebars and click Add New Turbo Sidebar.

Give the widget a name ( in my case it will be "Header Widget") and click Update. Then copy the shortcode provided.

In your theme files, add a shortcode where you want to display alt text. I want to display text in the title, so in the Zerif Lite theme I'll edit the big_title.php file and replace the line:

Zerif_big_title_text_trigger(); to the line below: widgets_on_template("header_widget");

Click Update File to save the changes you made to your location targeting settings.

Step 3: Add a shortcode to the widget to display a custom greeting image

Go to Custom Content > Content by Country and click on the option “ Enable Content by Country Feature » (« Allow content by country"). By default, this option is disabled.

Then go to Appearance > Widgets. Here you will find the new widget " header_widget" You will also see a new Shortcode Widget listed in the available widgets section.

Drag Shortcode Widget onto header_widget . In the content area, paste the shortcodes for the Custom Content by Country widget. Here's my example:

Brr! It's cold outside!
Let's warm up your noggin! Looking for a great hat?
Sale on now!

The first shortcode will display " Brr! It's cold outside! Let's warm up your noggin! » to visitors from Australia, because for « show" set to " y » ( yes ).

The second shortcode will display " Looking for a great hat? Sale on now! " to all visitors who are not in Australia, as I have set for " show" meaning " n » ( no ).

The page contains a second welcome message for non-Australian visitors because I'm in Canada. If you have a VPN, turn it on and set your location to somewhere in Australia:

Looks good! But it’s obvious that some kind of geotargeting style for the site is needed.

Step 4: Add CSS Styles

The design that the Custom Content by Country plugin adds is quite simple. Open CSS file main or child theme and add following lines for simple design:

Cbc_content ( color:#ffffff; font-size:80px; )

Now update user interface to see what it looks like:

This is a very simple example of how geotargeting content presented on a WordPress site can work with personalized content. And also how to display content on the site for visitors from different countries.

Geotargeting content using plugins

There are many other plugins available to add geotargeting functionality to WordPress:

Geolify ( premium): This paid SaaS solution allows you to apply geotargeting to all site content, including redirects, links, content, popups, notification bars, images, JavaScript.
GEO my WordPress ( free ): This plugin works with posts, pages, and custom post types. It also works with BuddyPress, so members can add their location.
WP Geo ( free): Allows you to establish the user's physical location and insert this information using a Google map.
GEO my WP ( premium): The plugin offers advanced options for geotargeting content, including options for custom types and BuddyPress, auto-filling Google Places addresses, nearby places and current location user.
GeoIP Detection ( free): The plugin provides geographic location information determined by IP address, which can then be used in themes. Intended for developers who can then apply this information.
GeoTargeting Lite ( free): The geotargeting plugin uses shortcodes to display content to users based on their geographic location.
Geotargeting WP ( premium): This API service allows developers to geo-target content for any part of the site, including posts, pages, custom types posts such as WooCommerce products, widgets, menus and template files.

I once wanted to show advertising on one of the sites only for users from a certain country, since it was simply pointless for other visitors to watch it. Why annoy them once again or clutter up the space of the web page? unnecessary information. This, in principle, can apply not only to advertising, but also to regular content (widgets, information blocks, etc.). It would seem that the task is quite trivial, but its implementation is by no means so. This is a story of a search, a story about discoveries and thoughts about possible solutions.

In general, I started looking for plugins related somehow to geo targeting or geo location, or something similar. All solutions can be divided into the following conditional groups:

  • paid modules from 30 free days, with subscriptions starting at a dollar a month or prices around $49.99;
  • plugins from the official WordPress website that have not been updated for more than two years, which have been downloaded 100-200 times or with questionable ratings.
  • In the third group, I would identify compromise solutions from which you can at least choose something.

In total, I settled on three options.

Content By Location

The plugin is a bit old, it supports WordPress versions to 3.3.2, but I still decided to try it. Looking ahead, I will say that launching on WP 3.1 and WP 3.4.2 did not bring results. I tried to display information both in the widget and in the PHP code of the template - in vain. Perhaps you need to delve into the module in a little more detail. His idea is actually quite good.

The Content By Location module supports working with three geolocation services at once: smart-ip.net, hostip.info, maxmind.com.

Once installed, you will simply need to select one of them. Then a shortcode is used to display the text:

Your content

Here, instead of “country code”, put the country abbreviation in the format SO_3166-1_alpha-2 (nl, uk, us, ru, fr, etc.). Actually, the advantage is the support of several services at once, if suddenly one of them refuses to work. I tested the first two, the third is a free and local database of countries that you will need to download. It is used in many solutions. So, if you have time, experiment.

IP2Location Tags

The plugin allows you to easily receive/display various geo information about a user based on his IP address. At all this decision This is just one of many; there are a dozen or two modules for different CMSs.

All of them are available, but the IP and country database is another matter. Eat LITE version(free) and commercial. In addition, what adds complexity is that you will have to somehow connect this database, either by specifying the paths, or by correcting the database. You can't figure it out without basic development skills.

One of the positive things can be said to be very easy to use module after connection. For example the following code:

Your IP is (ip:ipAddress) You are came from (ip:countryName), (ip:regionName), (ip:cityName)

... will display information about your address, country, region and city. There are a lot of similar variables there. You can easily create functional sites similar to IP address finders.

I will say right away that this solution is not free, but it is very effective. Not everything is clear about the cost - the website says $25.00 or 5WMZ (either a typo, or you can buy it for 5 WMZ).

There are plenty of advantages here:

  • quick installation and many settings;
  • the IP database is updated automatically free of charge without regular payments;
  • in addition to solving the problem of geotargeting with displaying content for different countries, it allows you to perform a number of other functions (redirection, flags);
  • more or less support current versions WP up to 3.8.
  • The plugin code is not coded, you can study and edit it.

From the description, it looks like the author is using the free (LITE) IP database of the MaxMind GeoLite service, which I mentioned above. It is quite enough, and it is updated automatically. In general, for the specified set of functions, I consider the price of $25 more than acceptable. Foreign analogues will be more expensive. Of course, if you are an experienced web developer, you can try to implement everything yourself.

Geotargeting is the provision of specific content to website visitors based on their geographic location, usually a country or city, identified by their IP address.

This technique has been around for so long that it has become ubiquitous. Google provides search results tailored to your location, Amazon offers personalized home pages with recommended products, and eBay displays local currency.

A more recent example of geotargeting is WordPress itself. The current 4.8 release includes a new dashboard widget that displays upcoming events tailored to your geographic location:

Using Google Analytics to Determine Visitor Locations

You can use Google Analytics to learn more about your visitors and where they are coming from. To do this, log into the analytical service and go to the tab Audience > Demographics > Geo > Location:


You'll see a color-coded map of the world that matches your audience demographics. Below is a more detailed analysis, including countries where users are located, sessions, new users, bounce rate, transactions and revenue.

You can use this information to personalize content on your site. For example, based on the geodata in the Google Analytics profile above, you can:

  • Add a German translation to the site;
  • Allocate more time to promoting content to American audiences ( for example, organize promotions for weekends in the USA);
  • Inform German visitors that you are collecting their information in accordance with EU cookie law;
  • Connect with visitors by greeting them in a location-appropriate manner ( for example, say “G’Day! » Australian visitors);
  • Showcase customer reviews from the same geographic area as the user;
  • Let visitors from the US, Canada, Australia, UK and Germany know that you are delivering to their location.

Using Geotargeting in WordPress

Let's look at a simple example of using geotargeting for a website: displaying welcome messages to visitors from different countries.

Display a welcome message

Let's assume that you have launched an online store specializing in selling hats. Your caps are selling out quickly thanks to the summer heat. But there is still a stock of winter hats that are collecting dust in the warehouse. Luckily, winter in Australia is the perfect opportunity to attract customers in the southern hemisphere and clear out inventory.

In this example, I want to show an alternative greeting on my home page that is only displayed to visitors from Australia. Visitors from other countries will see a standard welcome message.

Step 1: Install plugins

To implement this example, we will use several free plugins available in the WordPress Plugin Directory:

  • Custom Content by Country ;
  • Widgets on Pages ;
  • Shortcode Widget.

Custom Content by Country is a simple plugin that uses shortcodes to display content based on users' location. We will use it to geotarget content. Let's start by using it to display an alternative greeting.

I want to display an alternative welcome message above the theme header, so I use the Widgets on Pages plugin to add a widget to the header.

The Shortcode Widget plugin makes it easy to use shortcodes on your site, without having to add a filter to your functions.php file or create a child theme.

Step 2: Create a custom widget

In this example geotargeting WordPress I use the popular free theme Zerif Lite. Here's what it looks like right after installation:


I want to display a custom greeting instead of the generic one included in the Zerif Lite theme. To do this I will use my own widget.

First, let's make a few changes to the theme we're using:

  • Replace the header image;
  • Remove the green button;
  • Let's replace the text of the red button.

Now let's create our own header widget using Widgets on Pages. Go to the tab Widgets on Pages > Turbo Sidebars and click Add New Turbo Sidebar.

Give the widget a name ( in my case it will be "Header Widget") and click Update. Then copy the shortcode provided.

In your theme files, add a shortcode where you want to display alt text. I want to display text in the title, so in the Zerif Lite theme I'll edit the big_title.php file and replace the line:

zerif_big_title_text_trigger(); to the line below: widgets_on_template("header_widget");

Click Update File to save the changes you made to your location targeting settings.

Step 3: Add a shortcode to the widget to display a custom greeting image

Go to Custom Content > Content by Country and click on the option “ Enable Content by Country Feature» (« Allow content by country"). By default, this option is disabled.

Then go to Appearance > Widgets. Here you will find the new widget " header_widget" You will also see a new Shortcode Widget listed in the available widgets section.

Drag Shortcode Widget onto header_widget . In the content area, paste the shortcodes for the Custom Content by Country widget. Here's my example:

Brr! It's cold outside!
Let's warm up your noggin! Looking for a great hat?
Sale on now!


The first shortcode will display " Brr! It's cold outside! Let's warm up your noggin!» to visitors from Australia, because for « show" set to " y» ( yes).

The second shortcode will display " Looking for a great hat? Sale on now!" to all visitors who are not in Australia, as I have set for " show" meaning " n» ( no).


The page contains a second welcome message for non-Australian visitors because I'm in Canada. If you have a VPN, turn it on and set your location to somewhere in Australia:


Looks good! But it’s obvious that some kind of geotargeting style for the site is needed.

Step 4: Add CSS Styles

The design that the Custom Content by Country plugin adds is quite simple. Open your main or child theme's CSS file and add the following lines for a simple styling:

Cbc_content ( color:#ffffff; font-size:80px; )

Now refresh the UI to see what it looks like:


This is a very simple example of how geotargeting content presented on a WordPress site can work with personalized content. And also how to display content on the site for visitors from different countries.

Geotargeting content using plugins

There are many other plugins available to add geotargeting functionality to WordPress:

Geolify (premium): This paid SaaS solution allows you to apply geotargeting to all site content, including redirects, links, content, popups, notification bars, images, JavaScript.
GEO my WordPress ( free): This plugin works with posts, pages, and custom post types. It also works with BuddyPress, so members can add their location.
WP Geo (free): Allows you to set the user's physical location and insert that information using a Google map.
GEO my WP (premium): The plugin offers advanced options for geotargeting content, including options for custom types and BuddyPress, auto-filling Google Places addresses, nearby places, and the user's current location.
GeoIP Detection (free): The plugin provides geo-location information determined by IP address, which can then be used in themes. Intended for developers who can then apply this information.
GeoTargeting Lite (free): The geotargeting plugin uses shortcodes to display content to users based on their geographic location.
Geotargeting WP (premium): This API service allows developers to launch geotargeting content for any part of the site, including posts, pages, custom post types such as WooCommerce products, widgets, menus, and template files.

May 25, 2015 at 2:23 pm

Geotargeting by city (region, country) for WordPress

  • PHP
  • WordPress

Reasons for creation

Recently I was asked to do geotargeting by city for a WordPress site. Having reviewed existing geotargeting plugins (including paid ones), I did not find even one that works with cities (countries only). Therefore, I decided to make my own, using some existing database for determining location by IP address. At first I started by developing a function in a template, but then I decided to create a plugin and post it on github, because I think that it might be useful to someone else.

Selecting a base

The first step was to choose a base. And this is probably one of the most complex problems. During the development process, I tried many options, even made CURL requests to sites that determined location by IP, and parsed them. But all of them were not accurate, for example, one Moscow IP identified it as Moscow, the other simply identified it as Russia. It was also necessary for the plugin to work not only with Russia, but also with Belarus and Ukraine. After trying a bunch of different databases, I settled on Sypex Geo. They have shareware and free versions of the databases. Shareware uses the REST API and returns data to xml form, json and jsonp. The free one can be downloaded as a file, you can also download a class to work with it. The shareware version is more accurate, but only provides 10,000 queries for free. Free version is also quite accurate and is updated on the website.

Functional

As I already wrote, I started not with a plugin, but with a function in the template. At first I thought only about the shareware version of the database, but the number of free requests ended in a day or two. Therefore, I switched to free, using ready class to work with the database file.

When developing the plugin, I decided to make a choice between local base and REST API. In the future I plan to make a button automatic update bases.

You can also return Russians and english names cities (countries, regions). In this regard, I made a choice of language.
I also encountered the need to include several cities in the list or, conversely, exclude some.

Setting up the plugin in the admin panel

Implementation

Since I rarely work with Wordpress (as with all CMS) and have never written plugins for it, I started reading how to write them and seeing how existing ones work. I took the idea of ​​implementation from existing geo-plugins. For a long time I thought about writing functionally or object-oriented. I decided to do it functionally, since the plugin is not big.

I will briefly describe his work.

When activating the plugin, we initiate two options: the type of database and the language in which we will enter names.

Register_activation_hook(__FILE__, "wp_sypexgeo_activation"); function wp_sypexgeo_activation() ( update_option("sgeo_language", "en"); update_option("sgeo_dbase", "loc"); )
Next add_filter("the_content", "geotargeting_filter"); add_filter("the_content_rss", "geotargeting_filter"); add_filter("the_excerpt", "geotargeting_filter"); add_filter("the_excerpt_rss", "geotargeting_filter"); call the function

geotargeting_filter

function geotargeting_filter($s) ( //parse Country preg_match_all("#\[" . GEOTARGETING_COUNTY . "\s*(in|out)=([^\]]+)\](.*?)\#isu" , $s, $country); //parse Country preg_match_all("#\[" . GEOTARGETING_REGION . "\s*(in|out)=([^\]]+)\](.*?)\#isu ", $s, $region); //parse Country preg_match_all("#\[" . GEOTARGETING_CITY . "\s*(in|out)=([^\]]+)\](.*?)\# isu", $s, $city); if (empty($country) && empty($region) && empty($city)) ( return $s; ) $base_type = get_option("sgeo_dbase"); if ($base_type == "loc") ( $ipdata = getLocInfo(); ) elseif ($base_type == "rm") ( $ipdata = getRemInfo(); ) if (!empty($country)) ( foreach ($country as $ i => $raw) ( $type = strtolower($country[$i]); $countries = strtolower(trim(str_replace(array("\"", """, "\n", "\r", "\t", " "), "", $country[$i]))); $content = $country[$i]; $countries = explode(",", $countries); $replacement = "" ; if ((($type == "in") && in_array($ipdata["country"], $countries)) || (($type == "out") && !in_array($ipdata["country" ], $countries))) ( $replacement = $content; ) $s = str_replace($raw, $replacement, $s); ) ) if (!empty($region)) ( foreach ($region as $i => $raw) ( $type = strtolower($region[$i]); $regions = strtolower(trim(str_replace(array(" \"", """, "\n", "\r", "\t"), "", $region[$i]))); $content = $region[$i]; $regions = explode(",", $regions); $replacement = ""; if ((($type == "in") && in_array($ipdata["region"], $regions)) || (($type = = "out") && !in_array($ipdata["region"], $regions))) ( $replacement = $content; ) $s = str_replace($raw, $replacement, $s); ) ) if (! empty($city)) ( foreach ($city as $i => $raw) ( $type = strtolower($city[$i]); $cities = strtolower(trim(str_replace(array("\"", " "", "\n", "\r", "\t", " "), "", $city[$i]))); $content = $city[$i]; $cities = explode( ",", $cities); $replacement = ""; if ((($type == "in") && in_array($ipdata["city"], $cities)) || (($type == " out") && !in_array($ipdata["city"], $cities))) ( $replacement = $content; ) $s = str_replace($raw, $replacement, $s); ) ) return $s; )

Where the current content comes. Depending on the type of database, a function is called to obtain data. Then there is a search for special tags in the template and checking them with location data. If the data matches, the structure is replaced with the content from the tags; if not, it is deleted.

Usage

To indicate a list of countries: Hello Belarus, Russia!
To specify a list of regions: Hello Moscow Region!
To indicate a list of cities: Hello Minsk, Brest!
If you want to select countries (regions, cities) other than those indicated, use “out”: Hello everyone except Minsk, Brest!

Example of use in a template:

Welcome to WordPress. This is your first entry. Edit or delete it, then start blogging! Our contacts: +375295552255+375475552255

Conclusion

I hope my plugin is useful to someone. If you have questions or suggestions, write. Also, if someone thinks that it is necessary to use another database (geoservice or something else), suggest it, I will add it or you can add it yourself.






2024 gtavrl.ru.