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?
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
:(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