Last active
August 29, 2015 14:08
-
-
Save johnsardine/cc381d97f89dcec2550c to your computer and use it in GitHub Desktop.
WordPress: Query by coordinates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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