dsoxcj7276
2018-03-10 03:41 阅读 42
已采纳

在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 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;
    }
    
    点赞 评论 复制链接分享

相关推荐