MySQL Wordpress 如果 usermeta meta_key 存在,请执行此操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9108218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 11:59:01  来源:igfitidea点击:

Wordpress if usermeta meta_key exists do this

mysqlwordpresskeymetadata

提问by Sweepster

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'.

用户的元数据存储在 wp_usermeta 表中,该表包含 umeta_id、user_id、meta_key 和 meta_value。本质上,我需要查看 user_id 是否有一个名为“test”的 meta_key。

I am aware of the get_user_meta() function but I can't get this to work the way I want...

我知道 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";
}

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.

这段代码的理论是,我检查 meta_key 'test' 是否包含一个 meta_value,如果为真,则执行 X 否则执行 Y。令人烦恼的是,并非所有用户都有一个 'test' 的 meta_key。因此,如果登录用户没有此元密钥,则代码不起作用。此外,我不想检查元键的实际值(我所关心的可以是 NULL),我只想知道登录用户是否存在这样的键。

Any ideas?

有任何想法吗?

回答by moffepoffe

if ($havemeta) { echo 'your stuff'; }

回答by Hyman

(TESTED) If you put trueas the last argument, according to documentation, it will return the value of the metadata field. Which means you have to put falseas last argument.

(已测试)如果您将其true作为最后一个参数,根据文档,它将返回元数据字段的值。这意味着您必须将其false作为最后一个论点。

$havemeta = get_user_meta($userID, 'test', false);

Then, as said in the other answer, you can check it

然后,正如在另一个答案中所说,您可以检查它

if ($havemeta)
    echo $havemeta;
} else {
    echo "No";
}