HTML5 GeoLocation and WordPress

Let’s say that we have WordPress post objects with geolocation parameters.(lattitude, longitude). And we want to create geo filter and show relevant products to our visitors. For example if the visitor enters the website from New York, we want to show him only New York related products.

It is possible yeah. There are several ways. We can use 3rd party solutions (such as GeoPlugin ) in the website backend and detect where the visitor is. But to wait response from 3rd party service at backend – actually is not good idea.

WordPress - get the visitor location

So let’s try to do something at frontend side.

This piece of code detects the visitor geolocation, saves latitude + longitude as a cookie. Then it makes simple reload. It runs once when the visitor visits your website first time. And if you run this script before wp_head, the visitor will not feel redirect. So it will look smooth.

But what will happen at the backend side then? The only thing we need to do at backend side is to detect if the needed cookie exists and do some filters for that.

In this sample we have created sample filter which will show only those products which latitude is between 39-40, and longitude is between 47-49.

It is also possible to enrich javascript side of this solution and integrate it with Google Maps Geolocation API. In this case backend side will be more simple. As we will not have to create difficult lat-long meta query filter. We will only write one single CITY meta key, and that’s all.


Discover more from WP DEV - Elvin Haci

Subscribe to get the latest posts sent to your email.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from WP DEV - Elvin Haci

Subscribe now to keep reading and get access to the full archive.

Continue reading