Skip to content

Instantly share code, notes, and snippets.

@johnsardine
Last active August 29, 2015 14:08
Show Gist options
  • Save johnsardine/cc381d97f89dcec2550c to your computer and use it in GitHub Desktop.
Save johnsardine/cc381d97f89dcec2550c to your computer and use it in GitHub Desktop.
WordPress: Query by coordinates
global $wpdb;
$selected_range_number = intval(100); // Km
$query_lat = str_replace(',', '.', strval($selected_address_lat_lng['lat']));
$query_lng = str_replace(',', '.', strval($selected_address_lat_lng['lng']));
$query_by_distance = sprintf('
SELECT
p.*,
(
(
ACOS(
SIN( %1$s * PI() / 180 )
*
SIN( latitude.meta_value * PI() / 180 )
+
COS( %1$s * PI() / 180 )
*
COS( latitude.meta_value * PI() / 180 )
*
COS(
( %2$s - longitude.meta_value )
*
PI() / 180
)
)
* 180 / PI()
)
*
60
*
1.1515
) AS distance
FROM %4$s p
LEFT JOIN %5$s latitude ON latitude.post_id = p.ID AND latitude.meta_key = "course_address_lat"
LEFT JOIN %5$s longitude ON longitude.post_id = p.ID AND longitude.meta_key = "course_address_lng"
HAVING distance < %3$s
ORDER BY CAST(distance AS DECIMAL(10,5)) ASC;
',
$query_lat,
$query_lng,
($selected_range === 'any') ? 10000000 : $selected_range_number,
$wpdb->posts,
$wpdb->postmeta
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment