Order wp_query by calculated field

Question

Hi I’m working on a store locator.
I have a custom post “clinics” where I save clinic details (address,.., lat, lng). Each time I publish a new clinic I save post_id, lat and lng also in a custom table “lat_lng_post”.

I’m able to search clinics within a specific distance using filter post_where in this way:

add_filter( 'posts_where' , 'location_posts_where' )


    function location_posts_where( $where )
        {
            // $lat  and $ lng are latitude and longitude of the searched point
            global $wpdb;    
            $where .= " AND $wpdb->posts.ID IN (SELECT post_id FROM lat_lng_post 
                 WHERE
                 (6371 * acos( cos( radians(" . $lat . ") )
                  * cos( radians( lat ) )
                  * cos( radians( lng )
                  - radians(" . $lng . ") )
                  + sin( radians(" . $lat . ") )
                  * sin( radians( lat ) ) ) ) <= 150 
                    ORDER BY 
                        ( 6371 * acos( cos( radians(" . $lat . ") )
                  * cos( radians( lat ) )
                  * cos( radians( lng )
                  - radians(" . $lng . ") )
                  + sin( radians(" . $lat . ") )
                  * sin( radians( lat ) ) ) ) ASC)";
                        return $where;
                    }

I get the clinics within the fixed distance (150km) but not ordered according to the distance. They are shown according to the post date.
I tried to set orderby to none:

$args = array (
    'post_type'              => 'clinica',
    'orderby'                => 'none'

);

But It didn’t work. How can I force to order by that ORDER BY rule I set in the query?

0
, dstyle76 7 years 2016-03-07T10:00:54-05:00 0 Answers 101 views 0

Leave an answer

Browse
Browse