Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

WordPress WPDB SQL – How to query two meta_key

I am trying to query two meta keys at once using my code:

SELECT * FROM wp_postmeta

WHERE meta_key = "listing_location_enabled"
AND meta_value = "yes"

AND meta_key = "listing_location_country"
AND meta_value = "INDIA"

But is not showing any results. Is my query correct?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No, your query is not correct. (Those meta tables are a notorious pain in the xxx neck to use correctly.) You need this query pattern. It joins wp_postmeta to itself.

SELECT lle.post_id,
       lle.meta_value listing_location_enabled.
       llc.meta_value listing_location_country
 
  FROM wp_postmeta lle
  JOIN wp_postmeta llc  ON lle.post_id = llc.post_id
 WHERE lle.meta_key = 'listing_location_enabled'
   AND lle.meta_value = 'yes'
   AND llc.meta_key = 'listing_location_country'
   AND llc.meta_value = 'INDIA'

Or, better yet if you’re writing code for WordPress, use its WP_Meta_Query facility.

$q = new WP_Query( array(
    'meta_query' => array(
        'relation' => 'AND',
        'lle' => array(
            'key' => 'listing_location_enabled',
            'value' => 'yes',
        ),
        'llc' => array(
            'key' => 'listing_location_country',
            'value' => 'INDIA',
        ), 
    )
) );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading