How to check if a post meta key/value pair already exists for a specific post
-
26-04-2021 - |
Question
I want to know if for a given post ID $post_id
, there is a metadata key and value pair stored that matches a given key $meta_key
and value $meta_value
pair.
I am not looking for ANY post that matches the condition, which could easily be achieved with:
get_posts(array(
'meta_key' => $meta_key,
'meta_value' => $meta_value
));
But instead, for the given $post_id
.
There are probably many different ways to do it:
For example with get_posts():
get_posts(array(
'post__in' => array($post_id),
'meta_key' => $meta_key,
'meta_value' => $meta_value
));
Or looping through all the post meta and checking them all.
$results = get_post_meta($post_id, $meta_key, false);
$found = false;
foreach($results as $result){
if($result == $meta_value){
$found = true;
break;
}
}
But I want to know if there is any builtin way to do it in WordPress. And if there is not, what the most efficient one would be.
La solution
According to the docs of get_post_meta()
, you could try
- relying on the return value of the
get_post_meta()
function, or - use the
get_post_custom_keys()
function.
N.B. If you're going for the first option, you could use the object operator ->
to get the meta value from the post, and circumvent having to call get_post_meta()
yourself. View it on Trac here.