简体   繁体   中英

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?

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;
  1. Add $distancefromcity to posts meta-data

  2. Make 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?

    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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM