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_comparearguments; -
Or, using the
meta_queryargument 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_postsfunction come from theparse_querymethod ofWP_Queryclass. You may check theparse_querymethod documentation for more details. -
Also, since the internal implementation related to post meta arguments is using the
WP_Meta_Queryclass, you will also find some details inWP_Meta_Queryclass andWP_Meta_queryconstructor documentations.
There are user contributed examples in these documentations with more advanced use cases, including multiple post meta comparisons in a single query.