I have a meta key which I would like to use to get all post meta data for a post where that one meta key matches a specific value, in one go.

Example: Post 1 has a meta_key called unique_number. I want to query for all the occurences where unique_number is a specific value, and then get all the meta data for the posts where unique numner is that value.

The way I found to do it now, is this way:

$args = array(
    'meta_key' => 'unique_number',
    'meta_value' => '12345'

$posts = get_posts( $args );

...then I have to loop through the result and use get_post_meta to fetch the meta data.

Is it possible to do this in one query, except many, with built in Wordpress functions, or do I have to write my own custom mysql query?


When you call get_posts WP will also retrieve and cache all the post meta, so your later calls to get the meta data shouldn't cause any more database queries.

| improve this answer | |
  • If a for loop using the get_post_meta per post id just hits the cache, then thats ok. I could use a WP_Query, but why? – ptf Jul 25 '16 at 9:56
  • Ha. I'm not awake. I'm muddling get_posts and query_posts. Ignore that bit - I'll remove it. Generally though, ask yourself if you need to throw away the query that WP has already made and run a new one too. If not then modifying the main query will give you better performance. – Andy Macaulay-Brook Jul 25 '16 at 9:59

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.