WordPress Sort the posts returned by WP_Query

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?

Read More

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;

Related posts

2 comments

  1. I did it the following way.
    Is this Ok or is there any better way?

        while ($prop_selection->have_posts()): $prop_selection->the_post(); 
    
            $property_lat = 0;
            $property_lng = 0;
    
            $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);
            $distance_array[]= array( 'ID' => $post->ID,
                                    'distance' => $distancefromcity);
    
        endwhile;
    
    
        usort($distance_array, function ($item1, $item2) {
            if ($item1['distance'] == $item2['distance']) return 0;
            return $item1['distance'] < $item2['distance'] ? -1 : 1;
        });
    
    
        $sorted_posts = array();
    
        foreach($distance_array as $key)
        {
            $sorted_posts[]=$key['ID'];
        }
    
    
        $args = array(
            'cache_results'           =>    false,
            'update_post_meta_cache'  =>    false,
            'update_post_term_cache'  =>    false,
            'post_type'               =>    'estate_property',
            'post_status'             =>    'publish',
            'paged'                   =>    $paged,
            'posts_per_page'          =>    $prop_no,
            'post__in'                =>    $sorted_posts,
            'orderby'                 =>    'post__in'
        );
    
        $prop_selection =   new WP_Query($args);
    

Comments are closed.