WordPress 如果 usermeta meta_key 存在则执行此操作
我相信这对你们所有人来说都很容易,但对我来说这是全新的。
基本上,我想检查登录用户的个人资料中是否附加了某些元数据,某些内容是否会显示在网站上。
用户的元数据存储在wp_usermeta表中,该表包含umeta_id、user_id、meta_key和meta_value。本质上,我需要查看 user_id 是否有一个名为“test”的元密钥。
我知道 get_user_meta() 函数,但我无法让它按照我想要的方式工作...
global $current_user;
get_currentuserinfo(); // wordpress global variable to fetch logged in user info
$userID = $current_user->ID; // logged in user's ID
$havemeta = get_user_meta($userID, 'test', true); // stores the value of logged in user's meta data for 'test'.
if (isset($havemeta)){
echo $havemeta;
} else {
echo "No";
}
这段代码的理论是,我检查 meta_key 'test' 是否包含 meta_value,如果 true 则执行 X否则做 Y。令人烦恼的是,并非所有用户都有“test”的 meta_key。因此,如果登录用户没有此元密钥,则代码将不起作用。此外,我不想检查元键的实际值(我关心的它可以是 NULL),我只想知道登录用户是否存在这样的键。
有什么想法吗?
I'm sure this is easy for you all but this is all new to me.
Basically, I want to check that if the logged in user has a certain metadata attached to their profile, certain things display on the site.
The user's metadata is stored in the wp_usermeta table which contains umeta_id, user_id, meta_key and meta_value. In essence, I need to see if user_id has a meta_key named 'test'.
I am aware of the get_user_meta() function but I can't get this to work the way I want...
global $current_user;
get_currentuserinfo(); // wordpress global variable to fetch logged in user info
$userID = $current_user->ID; // logged in user's ID
$havemeta = get_user_meta($userID, 'test', true); // stores the value of logged in user's meta data for 'test'.
if (isset($havemeta)){
echo $havemeta;
} else {
echo "No";
}
The theory of this code is that I check to see if the meta_key 'test' contains a meta_value, if true do X else do Y. The annoyance is that not all users have a meta_key of 'test'. Therefore, if the logged in user doesn't have this meta key, the code doesn't function. Besides, I don't want to check the actual value of the meta key (it can be NULL for all I care), I just want to know if such a key exists for the logged in user.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Wordpress >=3.3
建议的解决方案有一个警告:值为
false
的 meta_key 将给出漏报。要询问 WordPress 是否设置了 meta_key,即使该值为
false
,也请使用metadata_exists
:Wordpress >=3.3
There is a caveat with the proposed solution: a meta_key which value is
false
will give false negatives.To ask WordPress if a meta_key is set, even if the value is
false
, usemetadata_exists
:(已测试)如果您将
true
作为最后一个参数,根据文档,它将返回元数据字段的值。这意味着您必须将false
作为最后一个参数。然后,正如另一个答案所说,你可以检查一下
(TESTED) If you put
true
as the last argument, according to documentation, it will return the value of the metadata field. Which means you have to putfalse
as last argument.Then, as said in the other answer, you can check it