Skip to content

Instantly share code, notes, and snippets.

@Asikur22
Created August 20, 2024 10:15
Show Gist options
  • Save Asikur22/b666ae5822ae343eecc22e7ecce6b9e6 to your computer and use it in GitHub Desktop.
Save Asikur22/b666ae5822ae343eecc22e7ecce6b9e6 to your computer and use it in GitHub Desktop.
WP Nearby Posts with latitude & longitude with radius
function get_posts_within_radius($center_lat, $center_lng, $radius, $post_limit = 10) {
global $wpdb;
$sql = "
SELECT
p.ID,
p.post_title AS title,
lat_meta.meta_value AS latitude,
lng_meta.meta_value AS longitude,
(6371 * acos(
cos(radians(%f)) * cos(radians(lat_meta.meta_value)) *
cos(radians(lng_meta.meta_value) - radians(%f)) +
sin(radians(%f)) * sin(radians(lat_meta.meta_value))
)) AS distance
FROM
{$wpdb->posts} AS p
INNER JOIN
{$wpdb->postmeta} AS lat_meta
ON p.ID = lat_meta.post_id AND lat_meta.meta_key = '_latitude'
INNER JOIN
{$wpdb->postmeta} AS lng_meta
ON p.ID = lng_meta.post_id AND lng_meta.meta_key = '_longitude'
WHERE
p.post_type = 'post'
AND p.post_status = 'publish'
HAVING
distance <= %f
ORDER BY
distance
LIMIT %d;
";
// Prepare the SQL query with the provided parameters
$query = $wpdb->prepare($sql, $center_lat, $center_lng, $center_lat, $radius, $post_limit);
// Execute the query and fetch results
$results = $wpdb->get_results($query);
// Return the results as an array
return $results;
}
// Example usage:
$center_lat = 51.5074;
$center_lng = -0.1278;
$radius = 50; // 50 km
$post_limit = 10; // Limit to 10 posts
$posts = get_posts_within_radius($center_lat, $center_lng, $radius, $post_limit);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment