You can use the post meta arguments that get_posts
function already supports. So, there is no need to use get_post_meta
function in a PHP loop.
For your use case, post meta related arguments can be used in one of the two possible ways:
-
Either using
meta_key
,meta_value
,meta_compare
arguments; -
Or, using the
meta_query
argument which supports an array of different post meta checks and hence is more powerful.
Using any of these methods returns all the necessary post data in one go.
Method-1:
The following example uses meta_key
, meta_value
, meta_compare
arguments to achieve what you want:
function karma_get_pre_publish_posts() {
$args = array(
'post_type' => 'post',
'post_status' => 'draft',
'meta_key' => 'approve',
'meta_value' => 'pre-publish',
'meta_compare' => '='
);
return get_posts( $args );
}
Method-2:
The meta_query
argument on the other hand requires an array of one or more argument arrays to query the posts with related post meta.
Like this:
function karma_get_pre_publish_posts() {
// Yes, $meta_query argument has to be coded as an array of arrays.
$meta_query = array(
array(
'key' => 'approve',
'value' => 'pre-publish',
'compare' => '='
)
);
$args = array(
'post_type' => 'post',
'post_status' => 'draft',
'meta_query' => $meta_query
);
return get_posts( $args );
}
Further reading:
-
Post meta related arguments (or parameters) of the
get_posts
function come from theparse_query
method ofWP_Query
class. You may check theparse_query
method documentation for more details. -
Also, since the internal implementation related to post meta arguments is using the
WP_Meta_Query
class, you will also find some details inWP_Meta_Query
class andWP_Meta_query
constructor documentations.
There are user contributed examples in these documentations with more advanced use cases, including multiple post meta comparisons in a single query.