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>