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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0