Support » Developing with WordPress » Customize WP-Query for radius search

  • Hello,

    I need some help to convert this Radius Search SQL query into a WordPress Query.

    When I use this with a mySQL table it works but how do I use this with the wordpress query?

    $lat_set - entered by customer
    $lng_set - entered by customer
    $lat_post - custom field in Post
    $lng_post - custom field in Post
    $markers - CPT
    $search_distance - the wished search radius
    
    SELECT id, ( 6371 * acos( cos( radians( $lat_set ) ) * cos( radians( $lat_post ) ) * cos( radians( $lng_post ) - radians( $lng_set ) ) + sin( radians( $lat_set ) ) * sin( radians( $lat_post ) ) ) ) AS distance FROM $markers HAVING distance < $search_distance ORDER BY distance LIMIT 0 , 20;

    Any suggestions?

    Thanks,
    Denis

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi DenisCGN,

    Give it a try with this:

    
    global $wpdb;
    $results =  $wpdb->get_results('SELECT id, ( 6371 * acos( cos( radians( '.$lat_set.' ) ) * cos( radians( '.$lat_post.' ) ) * cos( radians( '.$lng_post.' ) - radians( '.$lng_set.' ) ) + sin( radians( '.$lat_set.' ) ) * sin( radians( '.$lat_post.' ) ) ) ) AS distance FROM '.$markers.' HAVING distance < $search_distance ORDER BY distance LIMIT 0 , 20;');
    

    Thanks,
    Aliya

    @aliya-yasir

    Hello Aliya,

    thanks a lot. Is there a way to use the standard wordpress $meta-query so I can use my allready stored Lat&Lng custom fields?

    As far as I searched Google, this is somehow not possible.

    Cheers,
    Denis

    Moderator bcworkz

    (@bcworkz)

    I hope you all don’t mind my jumping in. Yes, not possible. It doesn’t appear your table is even a standard WP table. Even so, if it is or was made to be so, WP queries do not accept trigonometric functions as arguments. The closest you could get is items bounded within a particular lat/long “square”. The radial distance of items could be up to 41% greater than that specified since the corners are farther than the closest sides. In some cases that may be good enough, but the results are no longer within a certain radius.

    There are filters for WP queries where you could insert the necessary functions after WP has created the basic query. IMO you are better off using $wpdb methods to start with instead of hacking WP queries.

    FWIW, using spherical geometry to determine radial distance is not completely accurate either because the earth more ellipsoidal. Even an ellipsoid is an approximation, the earth is most correctly modeled as a “geoid”. Unless you are a land surveyor, none of this really matters, spherical geometry is more than close enough.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Customize WP-Query for radius search’ is closed to new replies.