I am performing distance wise sort on posts. scenario is like this: A user enters some city name, I get the coordinates for the city. Each post also have some coordinates as postmeta. I need to find the distance between these two points and sort the posts such as lowest distance post will show first.
I tried the following code for calculating distance which works fine. My problem is attaching this distance to the posts. I tried adding property to the post object. But then How to sort this posts?
I need the WP_Query object with sorted posts.
$prop_selection = new WP_Query($args);
while ($prop_selection->have_posts()): $prop_selection->the_post();
$property_lat = get_post_meta($post->ID,'property_latitude',true);
$property_lng = get_post_meta($post->ID,'property_longitude',true);
$distancefromcity=distance($property_lat,$property_lng,$city_lat,$city_lng,"K");
$distancefromcity=round($distancefromcity,2);
$post = (array)$post;
$post['distance'] = $distancefromcity;
$post = (object)$post;
endwhile;
Add
$distancefromcity
to posts meta-dataMake a custom select query and sort by distance. See
http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query
I did it the following way.
Is this Ok or is there any better way?