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 badges1 Answer
Reset to default 2According 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
版权声明:本文标题:How to check if a post meta keyvalue pair already exists for a specific post 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741619412a2388721.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论