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 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择