3

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?

  • try putting the order by into the filter posts_orderby. reference – iantsch Mar 13 '16 at 23:14
  • It means that I have to use LEFT JOIN? I'll try. – dstyle76 Mar 16 '16 at 13:58
  • no it doesn't. there is a filter for WHERE clause and also for ORDER BY. You just have to separate your code. – iantsch Mar 16 '16 at 16:38
  • 1
    and ignore the $args orderby... you filter posts_order_by for your CPT and this should overwrite any other orderby given by $args. edit where did you get your $lat resp. $lng in the code. if they aren't defined, they will return 0; – iantsch Mar 16 '16 at 16:56
0

Using WP_Query, you can order the results by meta_value_num:

$args = array (
    'post_type' => 'clinica',
    'meta_key'  => 'distance_field_name',
    'orderby'   => 'meta_value_num',
    'order'     => 'DESC'
);
| improve this answer | |
  • 2
    I don't have that field. The distance is calculated using the havering formula inside the post_where and lat and lng are stored in a custom table. – dstyle76 Mar 10 '16 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.