Shahnawaz Khan
Shahnawaz Khan

Reputation: 13

How to Automatically Detects User's Location and Display in Wordpress Page

I have developed a Custom wordpress Theme and i want to detect the user's location and get inside dropdown?

Upvotes: 0

Views: 6068

Answers (1)

rank
rank

Reputation: 2534

To locate a users position you can use the HTML Geolocation API. Check out the documentation: https://www.w3schools.com/html/html5_geolocation.asp

Like in the example of w3schools you only need something to trigger the javascript function. This can be your dropdown element, just give the attribute onclick="getLocation()" to it. Give the element where you want to output the location an ID, so you can put the result of the function in it.

Then you can put the following javascript in the footer.php file of your wordpress theme, or anywhere you think it fits your setting best.

Taken from: https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_geolocation

<script>
var x = document.getElementById("your_dropwdown_id");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
}
</script>

So on click of the element with the onclick="getLocation()" attribute, the getLocation() function is fired. The function gets the browser location data and outputs the result inside of the element with the id your_dropdown_id.

Hope this helps!

Upvotes: 1

Related Questions