Return to Snippet

Revision: 70519
at March 23, 2016 16:08 by JoshChris


Initial Code
$latitude = '30.050000';
$longitude = '-100.025000';

$query = "
SELECT ID, post_title, 
	(
		(
			(
				acos(
					sin(
						(".$latitude."*pi()/180)
					) * sin(
						(latitude.meta_value*pi()/180)
					) + cos(
						(".$latitude."*pi()/180)
					) * cos(
						(latitude.meta_value*pi()/180)
					) * cos(
						(
							(".$longitude."- longitude.meta_value)*pi()/180
						)
					)
				)
			)*180/pi()
		)*60*1.1515
	) AS distance
FROM $wpdb->posts
INNER JOIN $wpdb->postmeta latitude
    ON (ID = latitude.post_id AND latitude.meta_key = 'latitude')
INNER JOIN $wpdb->postmeta longitude
    ON (ID = longitude.post_id AND longitude.meta_key = 'longitude')
ORDER BY distance
LIMIT 0,50;
	";
$posts = $wpdb->get_results($query, OBJECT);

Initial URL

                                

Initial Description
A quick query example for a wordpress database query that gets posts ordered by distance via the custom fields `latitude` and `longitude`.

Initial Title
Wordpress Query: Sort posts nearest proximity to farthest

Initial Tags
wordpress

Initial Language
PHP