0

I have many posts. Some have meta data, with a key called "foo".

How can I query for just the posts with the meta data "foo"? metadata_exists requires the post ID, I'm trying to get the post IDs!

2
  • 1
    You should be able to achieve this with WP_Query meta_query parameter. The docs on Custom Fields has some helpful examples.
    – Howdy_McGee
    Jul 21 '21 at 19:38
  • 1
    Note that doing this is expensive/slow, and will get slower as the size of your site and the number of visitors increases. This isn't always obvious as a small site with no visitors can run these queries quickly giving the impression that they scale up, but they don't. Use a custom taxonomy instead if you want to add flags/filters/searches.
    – Tom J Nowell
    Jul 21 '21 at 19:53
3

I think something like this should do the job:

$meta_query = array(
    array(
         'key'     => 'foo',
         'compare' => 'EXISTS',
    ),
);

$args = array(
    'meta_query' => $meta_query
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        $post_id = get_the_ID();
    }
} else {
    // no posts found
}

wp_reset_postdata();

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.