dsoxcj7276 2018-03-10 03:41
浏览 44
已采纳

在Wordpress中按距离重新排序发布结果

UPDATED final code is here. and I think it works perfectly.

<?php 
                        $my_query = new WP_Query($args_places_cafe);
                        $locations = array();
                        if ($my_query->have_posts()) { ?>                
                            <div class="yelp_bussines_wrapper"><div class="yelp_icon"><i class="icon-paw"></i></div> 
                            <h4 class="yelp_category">Cafe</h4>                         
                        <?php while ($my_query->have_posts()):$my_query->the_post();
                            
                            $locationp = get_field('place_address');           
                            $lat1 = $locationp['lat'];
                            $lon1 = $locationp['lng']; 
                            $lat2 = $gmap_lat;
                            $lon2 = $gmap_long;
                            $dist = distance($lat1, $lon1, $lat2, $lon2, "K");
                            $title = get_the_title();
                            $locations[] = array(
                                'title'    => $title,
                                'dist'     => round($dist, 1)
                            );
                        endwhile;   
                        
                        usort( $locations, 'sort_locations' );

                        foreach( array_slice($locations, 0, 3) AS $location ) {
                            print '<div class="yelp_unit"><h5 class="yelp_unit_name">'.$location['title'].'</h5>';
                            print '<span class="yelp_unit_distance"> ('.$location['dist'].' km)</span></div>';
                            }
                        }
                        
                        function sort_locations( $a, $b ) {
                        if ( $a['dist'] == $b['dist'] ) {
                        return 0;
                            }

                            return ($a['dist'] < $b['dist'] ) ? -1 : 1;
                        }
                        wp_reset_query();   
                        ?>


I'm trying to order post by distance(coordinate) between two post types. For example, if you see 'Property' post, it shows related 'Place' posts (in same city). The problem is that I don't know how to re-order post results by distance.

Here's some explanation for the current code.

  • Two type of posts are have got geo data (latitude/longitude) each.
  • $lat1 and $lon1: ACF Fields in Place (blog post)
  • $lat2 and $lon2: Custom Fields in Property (custom post type)

Current code:

// Args for Places
$args_places = array(
    'post_type'    => 'post',
    'category__in' => 168,
    'showposts'    => '3', 
    'orderby'      => 'rand',
    'tax_query'    => array(
        array(
            'taxonomy' => 'places-cities',
            'terms'    => $terms_city,
            'field'    => 'name'
        )
    )
);

/**
 * Get distance between 'Properties' and 'Places'
 */
function distance($lat1, $lon1, $lat2, $lon2, $unit)
{
    $theta = $lon1 - $lon2;
    $dist  = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist  = acos($dist);
    $dist  = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $unit  = strtoupper($unit);

    if ($unit == "K") {
        return ($miles * 1.609344);
    } elseif ($unit == "N") {
        return ($miles * 0.8684);
    } else {
        return $miles;
    }
}     

// Get Places
$my_query = new WP_Query($args_places);
if ($my_query->have_posts()) {                 
    while ($my_query->have_posts()) {
        $my_query->the_post();
        $location = get_field('place_address');           
        $lat1     = $location['lat'];
        $lon1     = $location['lng']; 
        $lat2     = $gmap_lat;
        $lon2     = $gmap_long;
        $dist     = distance($lat1, $lon1, $lat2, $lon2, "K");  
        get_the_title();
        echo round($dist, 1).' km';
    }               
}
wp_reset_query();      
</div>
  • 写回答

1条回答 默认 最新

  • douruobokui58233 2018-03-10 04:22
    关注

    You're not going to be able to do this directly with the query. You're going to need to load the places, calculate the distances, assign the locations to an array, then do a sort on the array utilizing usort.

    Here's your code, with the principles applied. Note that since you haven't given enough info for us to build / test this, this is just the key concepts - you may have to adjust things to get them working given your data, etc.

    // Load places into a custom WP query
    $my_query = new WP_Query( $args_places );
    // create an array to store the locations in....
    $locations = array();
    // loop over the query results
    if ( $my_query->have_posts() ) {                 
        while ($my_query->have_posts()):
            $my_query->the_post();                  
            $location = get_field('place_address');           
            $lat1 = $location['lat'];
            $lon1 = $location['lng']; 
            $lat2 = $gmap_lat;
            $lon2 = $gmap_long;
            $dist = distance($lat1, $lon1, $lat2, $lon2, "K");  
            $title = get_the_title();
            // load the values into the array so it's available for sorting
            $locations[] = array(
                'title'    => $title,
                'location' => $location
                'dist'     => $dist
            );
        endwhile;
    
        // sort the array by distance
        usort( $locations, 'sort_locations' );
    
        // NOW you can output the locations, as they are sorted by distance
        foreach( $locations AS $location ) {
             echo $location['title'];
             echo $location['dist'] . 'km';
             // ...etc
        }
    }
    
    // callable for usort.  Sorts the array based on the 'dist' array value
    function sort_locations( $a, $b ) {
        if ( $a['dist'] == $b['dist'] ) {
            return 0;
        }
    
        return ($a['dist'] < $b['dist'] ) ? -1 : 1;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog