admin管理员组

文章数量:1296847

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.

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.

Share Improve this question edited Apr 13, 2021 at 10:23 Álvaro Franz asked Apr 12, 2021 at 20:45 Álvaro FranzÁlvaro Franz 1,1001 gold badge9 silver badges31 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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.

本文标签: How to check if a post meta keyvalue pair already exists for a specific post