/ Published in: PHP
A quick query example for a wordpress database query that gets posts ordered by distance via the custom fields `latitude` and `longitude`.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
$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);