1

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?

0
1

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.

2
  • 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. Jul 25 '16 at 9:59
0

You should not query for post meta values. The post meta value field is of type TEXT and has no index so queries are very slow as soon as your post meta table gets bigger. Use post meta only for cosmetic data. If you have custom values that you want to query always use custom tables which can easily be integrated into WP_Query args or write your own sql query for direct access of those values. More details to that topic can be found in this article which compares performance of post metas vs custom tables and gives some code examples too.

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.