admin管理员组

文章数量:1289525

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?

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?

Share Improve this question edited Jul 26, 2016 at 11:15 Andy Macaulay-Brook 3,8593 gold badges19 silver badges44 bronze badges asked Jul 25, 2016 at 9:33 ptfptf 4232 gold badges8 silver badges21 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 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.

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.

本文标签: wp queryPerformance when getting post meta for post retrieved by meta value