Conditional to modify query results

I’ll admit, I’m not a PHP expert, nor am I familiar with all of the WordPress functions and hooks. I’ve been stuck on an issue, searching for help without much success, and I was hoping that someone could help point me in the right direction.

I have a form. The user selects a specialty, location, and distance (10 miles, 20, 50, etc). The results are queried from a custom post type and filtered to match the specialty. The posts have their latitude and longitude in the meta data but I am not sure how to bring this into the query. I want the posts to only show if their latitude/longitude is within proximity from the specified distance. I have the functionality written already to get their distance. The trouble I’m having is with the query and displaying the data properly.

Here are my current query arguments:

$args = array(
    'post_type' => 'team-members',
    'posts_per_page' => -1,
    'meta_query' => array(
        array(
            'key' => 'specialties',
            'value' => $_GET['specialization'],
            'compare' => 'LIKE'
        )
    )
);
$loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post();

This currently will display all the posts with the matching specialization, however, does not include anything involving the distance. So what I initially did was then set a conditional to check if the post was within the distance specified (don’t worry about these variables, they are displaying the correct data):

if ( $distance < $_GET['within'] ) {

The issue is that this condition is not factored into the query, and I am unable to sort by distance. Additionally, I have to set a counter in order to get a correct post “count”, plus it just feels hacked together. I feel like there is a foundational error here, and I can’t pinpoint it.

I hope this information was sufficient, and if you need anything clarified, please comment. I didn’t want to overwhelmingly provide more than was necessary.

2 Answers
2

here is the mysql query you can use to get the result having distance less then your value.

SELECT * , pm1.meta_value  as latitude, pm2.meta_value as longitude ,    
      (((acos(sin(([latitude]*pi()/180)) * 
          sin((pm1.meta_value * pi()/180)) + cos(([latitude]*pi()/180)) * 
          cos((pm1.meta_value * pi()/180)) * cos((([longitude] - pm2.meta_value)* 
          pi()/180))))*180/pi())*60*1.1515
      ) as distance

FROM wp_posts p
JOIN wp_postmeta pm1 ON pm1.post_id = p.ID AND pm1.meta_key = 'latitude'
JOIN wp_postmeta pm2 ON pm2.post_id = p.ID AND pm2.meta_key = 'longitude'
WHERE ID = 98
having distance < $_GET['within']

It will return all the post with distance is less then your $_GET[‘within’] value.

Leave a Comment