It is possible to do this using the function wp_get_current_user()
. This function will get the contents of the WP_User
class. It can be stored in a global variable:
global $current_user;
$current_user = wp_get_current_user();
$current_user
will then become an array matching the properties of WP_User
for the currently logged in user. If no user is logged in then it will simply return an array with the ID
having a value of 0
.
You could then do something like:
if ( 0 == $current_user->ID ) {
// Code for No User Logged In
} elseif ( 4122 = $current_user->ID ) {
// Code for $gold_member
} else {
// Code for everyone else
}
That being said, as Rup noted in his comment, WP User Roles is a more efficient way to determine this over ID. However, since $current_user
is multi-dimensional array, you will need to either write a function that returns true
or false
testing to see if the value exists in it or pull it out and create a second variable and test it:
$current_user_roles = $current_user->roles;
if ( in_array( "gold_member", $current_user_roles ) ) {
// Gold Member Code Here
} else {
// Code for everyone else here
}
I would recommend writing the function since you can potentially re-use it elsewhere and it doesn’t involve another variable/global.