0

I have below function to get nearby posts, and what I want to achevie is to get additional custom meta out of table "rate_review" how can I achieve it?

function get_nearby_locations2( $lat, $lng, $distance ) {
       global $wpdb;

    $earth_radius = 6371;

    $sql = $wpdb->prepare( "
        SELECT DISTINCT
            map_lat.post_id,
            p.post_title,
            p.ID,
            map_lat.meta_value as locLat,
            map_lng.meta_value as locLong,

             (
    6371 * ACOS(
      COS(RADIANS( %s )) * COS(RADIANS(map_lat.meta_value)) * COS(
        RADIANS(map_lng.meta_value) - RADIANS( %s )
      ) + SIN(RADIANS( %s )) * SIN(RADIANS(map_lat.meta_value))
    )
  ) AS distance



        FROM $wpdb->posts p
        INNER JOIN $wpdb->postmeta map_lat ON p.ID = map_lat.post_id
        INNER JOIN $wpdb->postmeta map_lng ON p.ID = map_lng.post_id
        WHERE 1 = 1
        AND p.post_type = 'beaches'
        AND p.post_status = 'publish'
        AND map_lat.meta_key = 'map_lat'
        AND map_lng.meta_key = 'map_lng'
        HAVING distance < '10'
        ORDER BY distance ASC",
        $lat,
        $lng,
        $lat
    );

    $nearbyLocations = $wpdb->get_results( $sql );

    if ( $nearbyLocations ) {
        return $nearbyLocations;
    }
}

Which returns columns:

post_id
post_title
ID
locLat
locLong
distance

1 Answer 1

2

You need to add another join:

 INNER JOIN $wpdb->postmeta rate_review ON p.ID = rate_review.post_id

Add the condition to your where clause:

 AND rate_review.meta_key = 'rate_review'

Now you can add it to your SELECT:

 rate_review.meta_value AS rate_review
6
  • One more question. How to get this meta value in query without any additional call to database?
    – Rafal
    Commented Oct 24, 2016 at 20:17
  • 1
    It's still one query with my solution, just one more join Commented Oct 24, 2016 at 21:06
  • I meant how to get meta or eg. 'distance' from this table in my query. Thank you for your help!
    – Rafal
    Commented Oct 24, 2016 at 22:13
  • distance will be a property of each object of the result Commented Oct 24, 2016 at 22:14
  • Still cant get it out of there. Sorry to bother you, but could you please show how exactly would you call it?
    – Rafal
    Commented Oct 24, 2016 at 22:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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