Skip to Main Content

Search by Location with WP Query

I get a lot of client requests for “Store Locators” or “Location Finders”. There are some plugins like MapPress and WP Store Locator that work well for simple Location Searches, but as soon as the client has requests for specific functionality or designs, these pre-made options start to fall short, and you end up spending more time fighting their code than writing your own.

What makes it especially frustrating is that, using the Google Maps API most of the features of a store locator or location finder are fairly easy to write. The only hard part is getting posts that are within a certain distance from a specific latitude and longitude. This requires a somewhat complicated trigonometric formula called The Haversine Formula, to calculate distance between two points on a sphere.  All the other filters and selections can be handled with a simple WP Query, but distance is a trickier beast.

ADVERTISEMENT:

Most of the existing plugins that I’ve seen do a great job at the distance calculation, but don’t include much of a framework for building more complicated queries that match post meta and taxonomies. So I wrote one that comes at things from the other direction. It takes the standard WP Query that offers so much flexibility, and adds a geo_query option that will calculate distance from a point.

You use it like this:

<?php
$query = new WP_Query(array(
	// ... include other query arguments as usual
	'geo_query' => array(
		'lat_field' => '_latitude',  // this is the name of the meta field storing latitude
		'lng_field' => '_longitude', // this is the name of the meta field storing longitude 
		'latitude'  => 44.485261,    // this is the latitude of the point we are getting distance from
		'longitude' => -73.218952,   // this is the longitude of the point we are getting distance from
		'distance'  => 20,           // this is the maximum distance to search
		'units'     => 'miles'       // this supports options: miles, mi, kilometers, km
	),
	'orderby' => 'distance', // this tells WP Query to sort by distance
	'order'   => 'ASC'
));

In addition, there are two included functions that can be used to retrieve distance in the resulting loop: the_distance() and get_the_distance(). Both support two optional variables: a post object, and the number of integers to round the distance to.

The full code for the plugin is included below.

28 Comments

    • gschoppe's profile image.

      I’m working on a plugin to simplify the process, but in general, you would use the google maps api (i like using gmaps.js to simplify the API calls) to geocode a search field, into latitude and longitude, then, once you have lat and lng, you send them to an ajax function that runs the query from this post.

      • DaniB's profile image.

        Hello again! I’m revisiting this code because I need to hook my posts up to a google map search field. I have set it up per your suggestion on an earlier comment (send the lat/long to an ajax function that runs the query) however when I get the results back the posts are not sorted, and the output from the_distance(); is blank, even if I’m just running the same query with hardcoded lat/long on submission of the ajax form. Is there anything you can recommend I try to fix this, or were you ever able to complete the plugin mentioned in your previous comment to simplify it?
        Please let me know! This is an amazing plugin, thank you so much for sharing it. I almost have everything working how I need it to 🙂

  1. chris's profile image.

    Can this be used in combination with Toolset maps? I’m using Toolset to create custom posts, but want to sort them by distance.
    So when a user searches a city it takes the center of the city and sort by distance from that point..

    link to toolset

  2. Chris's profile image.

    This is awesome and exactly what I was looking for. I got it working but am trying to figure out how to get the get_distance() to round off? I can return the value but it has like 15 digits after the decimal point. How do I round it?

    • gschoppe's profile image.

      get_the_distance() and the_distance() each have a second argument for rounding. So, if I want to use the current global post object, and echo the distance to two decimal places, I would use the_distance(null, 2); If I wanted to make sure it was always exactly two decimal places, i would use echo number_format(get_the_distance(null, 2), 2, '.', '');.

    • gilli's profile image.

      Do you use it with toolset? Is it possible to get the modifications you made because i have a problem with toolset, it tooks to long with 20000 entries to get results on the map.

      kind regards
      gilli

      • gschoppe's profile image.

        It sounds like you are running into the limitations of doing a geo_query that relies on WordPress’s post_meta table, to perform faster for large data sets, you would want to do a few things:

        1. store latitude, longitude, and associated postID into a dedicated table with indexes on lat and lng
        2. modify the query to join this external table on postID, rather than doing two joins on the meta table, and refactor the rest of the query to reference the latitude and longitude fields in that table
        3. add a basic “bounding box” term to the search query, to allow SQL to quickly exclude all posts not within a bounding box before doing the more complex distance calculation

        I have been toying with the idea of extending this code to optionally support this sort of implementation. it’s no where near as easy to implement as a user, so I have put it off for a long time, but it is something I may come back to.

  3. Rob's profile image.

    Hi, when I install the plugin it works fine, but wp asks me to update it, and it takes me to https://wordpress.org/plugins/geo/ which is well outdated, matter of fact, when I update it, it doesn’t work anymore. Can we avoid to assk for updates or can you create your own updatable plugin? Thanks a lot

    • gschoppe's profile image.

      Hi Rob,

      Plugin updates are identified by filename, so it sounds like you saved the plugin file as `geo.php`, which matched the filename of that outdated plugin. If you change the filename to `wp-geo-query.php` the notice about an available update should go away.

  4. Berend's profile image.

    Is it possible that this class causes an inaccurate $wp_query->found_posts number? I’m getting non-zero numbers in there when the actual results are zero based on the geo_query. The $wp_query->posts array is empty.

    • gschoppe's profile image.

      it seems unlikely that the found posts count would be inaccurate as all the filtering and trimming is wholly contained in the SQL itself. Would you be able to share an example of code that is showing you an incorrect result?

  5. Roberto's profile image.

    Hi, using this plugin, and I absolutely thank you once again for this. I have one question in regards of REST, given 2 web sites, SiteA and SiteB, let’s say I want to get SiteB content within SiteA using REST, what I receive is a big json with all SiteB posts proprieties, I have even added custom fields in the json in order to read them by parsing the json in SiteA. Now the big question: how can I use the geoQuery to query the received URL json from SiteB in order to display its content on SiteA but queried? Thanks a lot

    • gschoppe's profile image.

      Sorry for the late response. I only just now saw this comment trapped in my spam filter.

      There is no built-in REST endpoint for geo_queries, so you would need to register a custom REST endpoint on SiteA, using register_rest_route()

      • Rob's profile image.

        Thanks for the reply. Could you provide an example? Because the way I have ended up is by using the formula with JS and do the geo query using that. I’m not sure how would you register any end point to geo query. Would you be able to post an example in regards? Thank you.

  6. Koji's profile image.

    I hit a bit of a weird issue while using this plugin while injecting “geo_query” data into a query via the action ‘pre_get_posts’.


    function insert_geodata( $query ) {
    if ( is_admin() || !$query->is_post_type_archive( 'location' ) )
    { return; }

    $geoQuery = array(
    array(
    'lat_field' => 'location_latitude',
    'lng_field' => 'location_longitude',
    'latitude' => '46.316',
    'longitude' => '-72.6833',
    'distance' => '25',
    'units' => 'km',
    )
    );

    $query->set( 'geo_query', $geoQuery );
    $query->set( 'orderby', 'distance' );
    }
    add_action( 'pre_get_posts', 'insert_geodata' );

    So… Yeah! Just a heads up; the WP Geo Query plugin doesn’t seem to catch this.

    • gschoppe's profile image.

      I’m sorry to be replying so late, but I only just saw this comment caught in my spam filter. The issue you are having is that unlike a meta_query or tax_query, a geo_query is an array of values, not an array of arrays. The double array syntax that you’re using is causing it to fail. This does raise some interesting possibilities for more complex searches, however, so I may look into modifying this code in the future to work with multiple concurrent geo_queries.

  7. R Rae's profile image.

    I have a custom table where i keep latitude, longitude along with post ID, unique row ID and other info in their own columns. Getting one row will return all of the location data as well as other info at once. I want to work with this code to adapt it to our custom table. Where do you think would be the best place to start?

    • gschoppe's profile image.

      You’d need to modify the queries pretty heavily to work with a dedicated table. The general concept would be to do an inner join between your custom table and the post table (replacing the two inner joins on line 50 and 51), strip out the part of line 77 that filters by meta_key, and modifying the haversine formula to use the correct fields from your dedicated table.

  8. Oscar's profile image.

    Hello Greg, thanks for your superb job! I’m trying to adapt your solution for using it with Custom Post Types, but I can’t get it working properly. Do I need to modify any code for using CPT?

    • gschoppe's profile image.

      You should be able to apply this plugin to a CPT by simply adding the ‘post_type’ argument to the wp_query, as usual. If you are still having issues, just shoot me an email with your custom query code in it to [email protected], and I’ll see what I can figure out.

  9. DaniB's profile image.

    Hello! Quick question regarding this. In my theme I have a custom post type and the latitude and longitude fields are set up with Advanced Custom Field’s Google map field. With ACF the lat and long values are stored together in one meta field, and I would get them like this normally:

    $gmap = get_field(‘google_map’);
    $lat = $gmap[‘lat’];
    $lng = $gmap[‘lng’];

    Would you have an idea on how I would modify your code to use the values from those fields? Everything I’ve tried so far has sadly turned up zero results. Any help is appreciated!

    • gschoppe's profile image.

      As I understand it, ACF normally stores Lat and Lng as part of a single serialized postmeta field, which isn’t really usable for geo queries. To fix this you would need to add a snippet to your functions.php that updates the value of a hidden latitude field and longitude field, whenever ACF saves a map value. You can see code for this in the first response to the linked forum post.

      You would also need to run through the site making sure this hidden field is set for any map items that have already been saved.

      Once this is complete, you could use my geo_query plugin to do the actual search, by just setting the fields to your hidden lat field and lng field.

      • DaniB's profile image.

        Hi Greg, thank you so so much for your help! That did the trick. In case anyone else has the same issue and to avoid my frustration, there’s one small correction to the answer in the link.

        add_action('acf/update_value', 'wpq_update_lng_and_lat', 99, 3 );

        function wpq_update_lng_and_lat( $value, $post_id, $field ) {
        if( 'google_map' === $field['type'] && 'google_map' === $field['name'] ) {
        update_post_meta( $post_id, 'my_lat', $value['lat'] );
        update_post_meta( $post_id, 'my_lng', $value['lng'] );
        }
        return $value;
        }

        You need to return $value otherwise when you save your ACF fields the data will disappear.

        Thank you so much for this plugin :)

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>