关你需要另一个INNER JOIN
应该使用$wpdb->prepare
.
我还加入了一个更有效的哈弗森公式(source) 来计算半径。
如果使用公里数,则更改$earth_radius
至6371。
此外,一种很好的调试方法是回显sql并将其粘贴到phpMyAdmin(或您使用的任何db应用程序)中,然后在其中进行调整。
function get_nearby_locations( $lat, $lng, $distance ) {
global $wpdb;
// Radius of the earth 3959 miles or 6371 kilometers.
$earth_radius = 3959;
$sql = $wpdb->prepare( "
SELECT DISTINCT
p.ID,
p.post_title,
map_lat.meta_value as locLat,
map_lng.meta_value as locLong,
( %d * acos(
cos( radians( %s ) )
* cos( radians( map_lat.meta_value ) )
* cos( radians( map_lng.meta_value ) - radians( %s ) )
+ sin( radians( %s ) )
* sin( radians( map_lat.meta_value ) )
) )
AS distance
FROM $wpdb->posts p
INNER JOIN $wpdb->postmeta map_lat ON p.ID = map_lat.post_id
INNER JOIN $wpdb->postmeta map_lng ON p.ID = map_lng.post_id
WHERE 1 = 1
AND p.post_type = \'beaches\'
AND p.post_status = \'publish\'
AND map_lat.meta_key = \'map_lat\'
AND map_lng.meta_key = \'map_lng\'
HAVING distance < %s
ORDER BY distance ASC",
$earth_radius,
$lat,
$lng,
$lat,
$distance
);
// Uncomment and paste into phpMyAdmin to debug.
// echo $sql;
$nearbyLocations = $wpdb->get_results( $sql );
if ( $nearbyLocations ) {
return $nearbyLocations;
}
}