Home » Wordpress » SQL and WordPress: Extract two custom fields with SQL

SQL and WordPress: Extract two custom fields with SQL

Posted by: admin November 30, 2017 Leave a comment


WordPress wp_postmeta table is constructed as a key/value pair:

ID | meta_key | meta_value

I need to get the values of two meta_keys within the result set:

property_lat and property_long

I will then use these values to assess the radius of a given point.


Two values in one result set:

FROM wp_postmeta 
WHERE meta_key IN ('property_lat', 'property_long')

Two values in one row:

SELECT (SELECT meta_value FROM wp_postmeta WHERE meta_key='property_lat' LIMIT 1) AS lat, 
       (SELECT meta_value FROM wp_postmeta WHERE meta_key='property_long' LIMIT 1) AS lng


Preterm’s solution can never get you all lat/longitude pairs at once. It can only get you the pair for one ID at a time. I’m not expert enough in SQL to guarantee that this will work right away, but I think you’re looking for something like this:

SELECT tbl.ID, lat.meta_value, lng.meta_value
FROM wp_postmeta AS tbl
INNER JOIN wp_postmeta AS lat ON lat.ID = tbl.ID AND lat.meta_key='property_lat'
INNER JOIN wp_postmeta AS lng ON lng.ID = tbl.ID AND lng.meta_key='property_long'
WHERE meta_key IN ('property_lat', 'property_long')


With your help, I was able to construct my query:

SET @centerLat = '48.428289';
SET @centerLng = '-123.380585';

SELECT wp_posts.*,
( 3959 * acos( cos( radians( @centerLat ) ) * cos( radians( lat.meta_value ) ) * cos( radians( lng.meta_value ) - radians(@centerLng) ) + sin( radians( @centerLat ) ) * sin( radians( lat.meta_value ) ) ) ) AS distance

FROM wp_posts

LEFT JOIN wp_postmeta AS lat 
    ON lat.post_id = wp_posts.ID 
        AND lat.meta_key = 'property_lat'

LEFT JOIN wp_postmeta AS lng 
    ON lng.post_id = wp_posts.ID 
        AND lng.meta_key = 'property_long'

WHERE lat.meta_key IS NOT NULL

HAVING distance > 5

LIMIT 0 , 20

Thank you!