Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress if usermeta meta_key exists do this

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?

like image 915
Sweepster Avatar asked Feb 02 '12 06:02

Sweepster


2 Answers

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, use metadata_exists:

if ( metadata_exists( 'user', $user_id, $meta_key ) ) {

   ...

}
like image 96
JesusIniesta Avatar answered Oct 07 '22 12:10

JesusIniesta


if ($havemeta) { echo 'your stuff'; }
like image 27
moffepoffe Avatar answered Oct 07 '22 11:10

moffepoffe