A plain WP_Query cannot sort GeoDirectory listings by distance, because the coordinates are stored in the GeoDirectory detail table and not in post meta. Use one of the options below.
Listings near the one being viewed
To show nearby listings on a listing page, no code is needed. Add the GD > Listings block to your details template page and set Sort by to “Distance to current post (details page only)”. The block then lists other listings ordered by distance from the one being viewed:
[gd_listings post_type="gd_place" sort_by="distance_asc" post_limit="5"]
Combine it with “Filter listings related to” if you only want nearby listings from the same category. To show how far each one is, add GD > Distance to Post to your archive item template.
Listings near any point
The search page already does this. A search URL with coordinates returns listings ordered nearest first, for example:
https://example.com/search/?geodir_search=1&stype=gd_place&s=&snear=&sgeo_lat=51.5072&sgeo_lon=-0.1276
Use the address of your own search page. Results are limited to the “Search near radius” set in GeoDirectory > Settings > General > Search, unless you add a dist parameter. If you start from a postcode, geocode it to latitude and longitude first, then pass those values.
Using the REST API
For your own code or an app, the markers endpoint returns listings within a radius of a point:
https://example.com/wp-json/geodir/v2/markers/?post_type=gd_place&lat=51.5072&lon=-0.1276&dist=10
dist is the radius in the unit set in GeoDirectory > Settings > General > Search (Search distances, miles or kilometers). Without it, the “Search near radius” setting is used. Each result has the listing ID (m), title (t) and coordinates (lt, ln).
The endpoint does not sort by distance by default. This snippet orders the results nearest first whenever coordinates are passed:
add_filter( 'geodir_rest_markers_query_order_by', function( $order_by, $request ) {
if ( ! empty( $request['lat'] ) && ! empty( $request['lon'] ) ) {
$order_by = 'distance ASC';
}
return $order_by;
}, 10, 2 );
See the API endpoints for the rest of the REST API.