I would like to create a wp_query that would return posts meta inside the posts
array.
$args = array (
'post_type' => 'page',
'meta_key' => 'someMetaKeyName',
);
// The Query
$query = new WP_Query( $args );
This returns something like:
As you can see the posts do not have any meta data, is it possible to include the meta data in the returned array as well?
PS I don’t want additional wp_queries for performance reasons.
By default, WP_Query
returns the standard WP_Post
objects for the posts being queried. I believe with some clever rewrite and use of the filters given in WP_Query
you can add objects to the returned WP_Post
objects array.
Will this be performant? In my opinion, it will hurt performance more as you will need to join results in your query as custom fields are not saved in the wp_posts
table, but in the wp_postmeta
table
Retrieving post meta is really fast and it does not require any extra instance of WP_Query
. You can simply call the custom field with get_post_meta()
. WordPress was very thoughtful when the custom fields was introduced. They added a cache to cache them, so whether you are querying 1 or 100 custom fields, you are hitting the database once, superfast. For a complete test and explanation, see this post I have recently done on this subject.
In my opinion, the extra database call and the actual time spent is worth it and faster than rewriting WP_Query
in such a way to include custom fields in the standard post object returned by $posts