Say I've got the custom post type foo with a meta box called bar. I've posted an entry with bar = pineapple. Now I want to check if there is a foo in the database with a bar set to pineapple. How would I do that?

I've managed to get this working using a wpdb query but that doesn't feel right. Is there an elegant, maybe built-in way for me to do this?

  • so the post meta key is bar and it's meta value is pineapple?
    – birgire
    Oct 9, 2013 at 0:39
  • @birgire Yes, in 1 post
    – Joren
    Oct 9, 2013 at 0:40

1 Answer 1


I think you mean a query like this one:

$args = array( 
               'post_type'      => 'foo', 
               'meta_key'       => 'bar', 
               'meta_value'     => 'pineapple',
               'posts_per_page' => 1,

$query = new WP_Query( $args );

You can check out further information here on meta queries in WP_Query.

If you only want to check if there exists such a post, you can use the found_posts property:

if( $query->found_posts > 0 ){
    // do stuff

or the usual way with the have_posts() method:

if( $query->have_posts() ){
    // do stuff

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.