繁体   English   中英

Wordpress对WP_Query返回的帖子进行排序

[英]Wordpress Sort the posts returned by WP_Query

我在帖子上执行距离明智的排序。 场景是这样的:用户输入了一些城市名称,我得到了城市的坐标。 每个帖子还具有一些作为后元的坐标。 我需要找到这两个点之间的距离并对帖子进行排序,例如最低距离的帖子将首先显示。

我尝试了以下代码来计算距离,效果很好。 我的问题是将此距离附加到帖子上。 我尝试将属性添加到post对象。 但是那该如何排序帖子呢?

我需要带有已排序帖子的WP_Query对象。

$ prop_selection =新的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. $distancefromcity添加到发布元数据

  2. 进行自定义选择查询,然后按距离排序。 参见http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query

我是通过以下方式做到的。 这样可以吗?还是有更好的办法?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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