- Реализуем геолокацию на WordPress-сайте с помощью GeoIP
- Разработка сайтов WordPress, определяющих георасположение с помощью GeoIP
- Кэширование и GeoIP
- Geolocation IP Detection
- Description
- Features:
- How can I use these functions?
- Troubleshooting
- Screenshots
- Installation
- Further documentation
- Reviews
- Great plugin, easy to use
- Great Plugin! Great Support!
- Support does not respond
- Excellent plugin with quality support
- Great plugin, great support
- Works well
- Contributors & Developers
- Interested in development?
- Changelog
Реализуем геолокацию на WordPress-сайте с помощью GeoIP
Онлайн-бизнес несет в себе одно важное преимущество – он позволяет охватить клиентов со всего мира. Естественно, такой подход создает уникальные сложности, поскольку пользователи в разных странах и регионах имеют специфические потребности, подпадают под разные законы. Если брать в качестве примера сайты электронной коммерции, то для них представление о посетителях (их географическом расположении) позволяет сразу же вычислять налоговые ставки. Некоторые товары, которые вы предлагаете, могут быть запрещены в тех или иных регионах, и этот вопрос также нужно рассмотреть.
Для таких сайтов очень важную роль играет геолокация, т.е. возможность программно распознавать расположение посетителя, регион, или даже долготу и широту. Обычно это делается при помощи базы данных GeoIP от Maxmind. Эта бесплатная база данных используется для перевода IP-адреса в геолокационные данные.
Есть несколько WordPress-плагинов, которые используют эту базу данных, чтобы создавать интересные вещи. К примеру, есть плагин, который позволяет автоматически переключаться на переведенную версию сайта, если такая доступна в WPML, на основе региона пользователя. Есть даже расширение для WooCommerce, которое позволяет устанавливать разные цены в зависимости от географического расположения пользователя.
GeoIP – очень полезная технология для всех типов приложений. Вычисление налога с продаж на основе географического расположения стало очень важным фактором вследствие изменений в европейских законах VAT (налог на добавленную стоимость). Также можно привести приложения, которые выводят рекламу в зависимости от географического расположения; существуют приложения, которые блокируют продажи определенных продуктов на определенных рынках.
Разработка сайтов WordPress, определяющих георасположение с помощью GeoIP
GeoIP Detect – это бесплатный плагин, который автоматически обновляет базу данных GeoIP и предлагает вам набор полезных функций для получения специфичной в плане географического расположения информации о пользователях (на основе IP-адреса).
После своей установки плагин предложит вам установить свежую базу данных GeoIP. Как только это будет выполнено, вы будете перенесены на экран настроек.
Здесь вы можете вручную обновить данные GeoIP – сам плагин будет автоматически обновляться раз в месяц. Вы можете также добавить класс с кодом страны к тегу body. Если ваша тема использует функцию body_class() (как это обычно и происходит), вы можете использовать данный тег для создания специальных правил CSS для разных географических локаций.
Плагин дает вам практически все, что вам нужно для создания контента, зависящего от географического расположения. К примеру, если вы хотите отфильтровать заголовки записи, касающиеся, скажем, футбола, в зависимости от локации, вы можете написать следующее:
Мы используем функцию geoip_detect2_get_info_from_current_ip(), которая предлагается данным плагином. С ее помощью мы получаем код страны ISO, состоящий из 2 букв. Если этот код не является US, то в таком случае мы меняем слово soccer на football.
Это – упрощенный пример, однако я надеюсь, что вы поймете, как вы можете использовать данный тип информации о ваших пользователях для генерации динамического контента. К примеру, похожий код может использоваться для замены кнопки «Купить/Добавить в корзину» на уведомление о том, что данный продукт недоступен в соответствующей стране или в определенном регионе этой страны.
Свойство, расположенное в объекте, который функция возвращает, содержит массив полезной информации. Следующий фрагмент кода демонстрирует, как получить долготу, широту и часовой пояс текущего пользователя. Затем вы сможете использовать эти данные для вывода магазинов, ближайших к пользователям, со временем работы, которое будет задано в верном часовом поясе. Или вы можете использовать код для направления посетителей к самому подходящему событию.
Кэширование и GeoIP
Проблема GeoIP – то, что определение геолокации не работает с традиционной полностраничной системой кэширования. Обычно такая система хранит обработанный HTML-файл каждой страницы на вашем сайте. Таким образом, системе просто нужно создать страницу, выполнив весь PHP-код и запросы к базе данных, которые она включает. Естественно, если у вас всего одна версия вашего сайта, которая выдается всем пользователям, то в таком случае любой тип динамического контента, как, к примеру, контент, зависящий от географического расположения, не будет работать.
Решение этой проблемы – использование фрагментарного кэширования. Этот метод, известный как частичное кэширование страницы, позволяет вам кэшировать определенные участки страницы, или даже только запросы к базе данных, в то время как динамично генерируемый контент будет загружаться на странице. Такая методика часто используется на сайтах сообществ, которые имеют небольшой объем контента, выводимого для разных пользователей.
Фрагментарное кэширование может быть полезным при работе с контентом, зависящим от геолокации, поскольку вы можете кэшировать нединамический контент, выводя при этом динамический контент, который зависит от географического расположения.
Я рекомендую кэшировать результаты поиска по базе данных GeoIP в недолговечных transient’ах. Вот простая функция, которая позволяет получить геолокационные данные для IP-адреса, при этом используя кэширование данных там, где это возможно:
Есть несколько плагинов кэширования, которые могут использовать разный кэш для географический версий сайтов, основанных на GeoIP. Следующая статья, опубликованная на WPtest, предлагает прекрасное описание опций, доступных для реализации кэширования, совместимого с GeoIP . С ростом известности GeoIP будут появляться все новые и новые плагины кэширования, которые будут иметь поддержку этого сервиса.
Geolocation IP Detection
Description
Provides geographic information detected by an IP adress. This can be used in themes or other plugins, as a shortcode, or via CSS body classes. The city & country names are translated in different languages (supported languages).
Features:
- You can use one of these data sources (see comparison):
- Free (default source): HostIP.info (IPv4 only)
- Free with registration: Maxmind GeoIP2 Lite City, automatically updated weekly
- Commercial: Maxmind GeoIP2 City or Maxmind GeoIP2 Country
- Commercial Web-API: Maxmind GeoIP2 Precision (City, Country or Insights)
- Hosting-Provider dependent: Cloudflare or Amazon AWS CloudFront (Country)
- Free or Commercial Web-API: Ipstack
- Commercial Web-API via AWS Marketplace: Fastah
- Provides these 5 functions (see API Documentation):
- geoip_detect2_get_info_from_ip($ip, $locales = array(‘en’), $options = array()) : Lookup Geo-Information of the specified IP
- geoip_detect2_get_info_from_current_ip($locales = array(‘en’), $options = array()) : Lookup Geo-Information of the current website user
- geoip_detect2_get_current_source_description(. ) : Return a human-readable label of the currently chosen source.
- geoip_detect2_get_external_ip_adress() : Fetch the internet adress of the webserver
- geoip_detect2_get_client_ip() : Get client IP (even if it is behind a reverse proxy)
- For the property names, see the results of a specific IP in the wordpress backend (under Tools > Geolocation IP Detection).
- You can include these properties into your posts and pages by using the shortcode [geoip_detect2 property=»country.name» default=»(country could not be detected)» lang=»en»] (where ‘country.name’ can be one of the other property names as well, and ‘default’ and ‘lang’ are optional).
- You can show or hide content by using a shortcode [geoip_detect2_show_if country=»FR, DE» not_city=»Berlin»]TEXT[/geoip_detect2_show_if] . See Shortcode Documentation.
- When enabled on the options page, it adds CSS classes to the body tag such as geoip-province-HE , geoip-country-DE and geoip-continent-EU .
- If you are using a page cache, it is recommended to use the AJAX mode (see AJAX)
- When enabled on the options page, the client IP respects a reverse proxy of the server.
- If you are using Contact Form 7, you can use these shortcodes:
- A select input with all countries, the detected country being selected by default: [geoip_detect2_countries mycountry]
- A text input that is pre-filled with the detected city (or other property): [geoip_detect2_text_input city property:city lang:fr id:id class:class default:Paris]
- Geolocation information for the email text: [geoip_detect2_user_info]
- Together with SVG Flags you can show the flag of the detected country: [geoip_detect2_current_flag] (see documentation)
See Documentation for more info.
How can I use these functions?
- You could choose the currency of the store based on the country name
- You could pre-fill the shipping country
- You could show the store nearest to your customer
- You show or hide content specific to a geographic target group
- Etc. … You tell me! I’m rather curious what you’ll do with this plugin!
- Be careful to comply to the applicable laws. For example Regulation (EU) 2018/302 …
- If you need to get the user’s timezone, it is more accurate to use JS solutions.
System Requirements: You will need at least PHP 7.2.5 If you use the plugin WooCommerce, you’ll need at least WooCommerce 3.9.0 .
This extension is “charity-ware”. If you are happy with it, please leave a tip for the benefit of this charity. (See FAQ for more infos.)
This product can provide GeoLite2 data created by MaxMind, available from http://www.maxmind.com.
Troubleshooting
- Does geoip_detect2_get_info_from_current_ip() return the same country, regardless of where you are visiting the site from?
- Maybe your server has a reverse proxy configured. You can check this: Go to the options page and look for “reverse proxy”. Are there 2 IPs listed there? If so, which one corresponds to your public IP?
- Or maybe you are using a site cache plugin. Then enable the option Disable caching a page that contains a shortcode or API call to geo-dependent functions.
Screenshots
Lookup page (under Tools > Geolocation Lookup)
Options page (under Preferences > Geolocation IP Detection)
Installation
- Install the plugin
- Go to the plugin’s option page and choose a data source.
- Test it by clicking on “Lookup” on the lookup page.
Further documentation
Reviews
Great plugin, easy to use
Great Plugin! Great Support!
Support does not respond
Excellent plugin with quality support
Great plugin, great support
Works well
Contributors & Developers
“Geolocation IP Detection” is open source software. The following people have contributed to this plugin.
“Geolocation IP Detection” has been translated into 2 locales. Thank you to the translators for their contributions.
Interested in development?
Changelog
- NEW: For the reverse proxy configuration, internal adresses (such as 10.0.0.0/8) are now whitelisted by default. You can override this behaviour by using the wordpress filter geoip_detect2_client_ip_whitelist_internal_ips .
- NEW: Body classes now include the city name in English (e.g. geoip-city-Munich)
- FIX: Some server configurations showed this warning: Use of undefined constant CURL_HTTP_VERSION_2_0
New Datasource: Fastah Web API (beta), see https://aws.amazon.com/marketplace/pp/prodview-k5gjowexrefl2
AJAX mode:
* NEW: The JS function geoip_detect.set_override_with_merge can modify the override record in one property, merging it with the currently saved property
Other minor changes:
* FIX: In non-AJAX mode, properties such as “extra.original.zip” can be accessed again
* FIX: Automatic download of Maxmind database now also works when the temp folder is group/world writeable (as in AWS configurations)
* If you want to enable more Warnings (e.g. while debugging), you can add define(‘GEOIP_DETECT_DEBUG’, true) to your wp-config.php or so.
* Library updates
In this release, there a small breaking changes marked by [!].
AJAX mode:
* FIX [!]: Empty attribute values such as [geoip_detect2_show_if country=»»]Country was not detected[/geoip_detect2_show_if] are now working (they were ignored before)
* FIX [!]: Shortcodes that have an invalid value for the property ajax (e.g. [geoip_detect2_text_input ajax=»invalid»] ) are now using the AJAX option instead of always disabling AJAX
* FIX: In CF7, the country selector can now be used in AJAX mode
* FIX: In AJAX mode, the shortcode [geoip_detect2_show_if] renders as a
Other changes:
* NEW: Drastically improving performance if the lookup is performed for the current IP more than once (e.g. because of shortcodes without AJAX mode)
* UI: Showing the time for the subsequent lookup on the Test Lookup page
* FIX: Maxmind Datasource: Check if the database file is really a file, not a directory
* NEW: Header Datasource: Now a custom HTTP header can be used via the wordpress filter geoip_detect2_source_header_http_key
Other minor changes:
* Update the list of available APIs for getting the external IP (as whatismyip went down)
* Minimum WordPress version is 5.4 now.
* Update some internal libraries & dev tools
* Checked compatibility with PHP 8.1
- FIX: Further improve the Maxmind admin notice UI
- Update some smaller libraries
- FIX: Show Maxmind admin notice only on GeoIP pages to make it less intrusive
- FIX: Do not disable lookup automatically when potentially incompatible Maxmind libraries are found.
- NEW: Show a warning on the options page when there are incompatibilities with other plugins that also use the Maxmind libraries.
- FIX: Remove an incompatibility of the libraries with Toolset or other Laravel-based plugins
- NEW: In CF7, you can now add any property to the mail body with a special syntax, e.g. [geoip_detect2_property_country__iso_code]
- FIX (JS): Replace the internally used library ‘lodash’ with ‘just’ to reduce the JS file size
- FIX (JS): Improve error handling in AJAX mode
- FIX: Port numbers in reverse proxies are ignored now (removes incompatibility with Azure reverse proxies)
- FIX: Prevent Cloudflare APO from caching when using AJAX mode or page caching is disabled in the plugin options
- NEW: An else shortcode for geoip_detect2_show_if and geoip_detect2_hide_if : [geoip_detect2_show_if city=»Berlin»]You are in Berlin[else]You are not in Berlin[/geoip_detect2_show_if]
- FIX: The JS for AJAX wasn’t working for Safari browsers
- FIX: Improving some edge cases of Record.get_with_locales() and other methods of Record to be consistent with non-AJAX mode
- FIX: Revert more Maxmind libraries to fix incompatibility with WooCommerce
- FIX: Revert Maxmind library to 2.10.0 for now as the most current version seems to be incompatible with Wordfence and other plugins using the older version of the Maxmind library
This version has many changes regarding the Shortcodes API. It is a major version because it increases some system requirements (see below).
- NEW: Shortcodes can now also be resolved in AJAX mode (without coding JS).
If you are using a page cache, AJAX mode is the best solution for you. And thanks to shortcodes, this doesn’t need custom coding anymore.
You can keep using the same shortcodes as before – just tick the options “Enable AJAX endpoint” and “Resolve shortcodes (via AJAX)”.
Instead of doing the geo-lookup while generating the HTML, it will generate boilerplate HTML (for the cache) that will be filled by the plugin’s JS automatically (in the client’s browser). - NEW: JS has a new function called set_override(record, duration_in_days) (see AJAX documentation) so that the record information can be overridden manually (e.g. when the user selects a certain country manually). A PHP equivalent will follow.
- NEW: The JS syntax of the shortcodes now supports both underscore_case and camelCase (e.g. both country.is_in_european_union and country.isInEuropeanUnion are valid)
- NEW: [geoip_detect2_show_if] and [geoip_detect2_hide_if] now have a new attribute operator=»OR» – this can be used to create conditions such as “continent = EU OR country = US”
Other Improvements:
* NEW (UI): Add a “Empty Cache”-Button on the Lookup page if the data source is caching the results
* FIX: In some cases, the Privacy Exclusions Update wasn’t rescheduled properly before
* FIX: Ipstack: The property country.isInEuropeanUnion is now filled properly.
* Updated vendor code
Also note:
* The minimum PHP version is now 7.2.5
* Minimum WordPress version is now 5.0
* The plugin is now using PHP Type-Hinting for API functions – if you used the PHP API, please check if you see PHP errors
* If you are using WooCommerce, you need at least version 3.9.0 (released Jan 2020) – otherwise this plugin lookup disables itself
As always, if you are happy about the plugin, please consider donating, becoming a Beta-Tester or otherwise contributing to it.