另一个解决方案建立在其他解决方案的基础上:
使用了$wpdb->;准备参数转义从$wpdb中使用的表名添加了最小距离添加了限制添加了在英里和公里之间切换的选项添加了设置后置类型的选项为元字段提取的名称
/**
* @param float $latitude Latitude of the center
* @param float $longitude longitude of the center
* @param int $min_distance Minimal distance from the center (Default: 0).
* @param int $max_distance Maximal distance from the center (Default: 100).
* @param int $limit Maximal number of results (Default: 20).
* @param string $post_type Post type to filter for (Default: \'pois\').
* @param boolean $use_miles Set to true, if you are using miles instead of kilometers (Default: false).
* @return array|object
*/
function my_get_nearby_locations( $latitude, $longitude, $min_distance = 0, $max_distance = 100, $limit = 20, $post_type = \'pois\', $use_miles = false ) {
global $wpdb;
$meta_key_latitude = \'location_lat\';
$meta_key_longitude = \'location_long\';
$miles_to_km = $use_miles ? 1 : 1.609344;
$query = "SELECT DISTINCT
t_lat.post_id,
t_post.post_title,
t_lat.meta_value as latitude,
t_long.meta_value as longitude,
((ACOS(SIN(%f * PI() / 180) * SIN(t_lat.meta_value * PI() / 180) + COS(%f * PI() / 180) * COS(t_lat.meta_value * PI() / 180) * COS((%f - t_long.meta_value) * PI() / 180)) * 180 / PI()) * 60 * 1.1515 * {$miles_to_km}) AS distance
FROM {$wpdb->postmeta} AS t_lat
LEFT JOIN {$wpdb->postmeta} as t_long ON t_lat.post_id = t_long.post_id
INNER JOIN {$wpdb->posts} as t_post ON t_post.ID = t_lat.post_id
WHERE t_lat.meta_key = %s AND t_long.meta_key = %s AND t_post.post_type = %s
HAVING distance > %d AND distance < %d ORDER BY distance ASC LIMIT %d;";
$prepared_query = $wpdb->prepare( $query, [ $latitude, $latitude, $longitude, $meta_key_latitude, $meta_key_longitude, $post_type, $min_distance, $max_distance, $limit ] );
return $wpdb->get_results( $prepared_query );
}