I'm building a membership site with a membership plugin right now. The different types of memberships are associated with IDs and I have to constantly do things like "show this if the ID is 4122 (i.e. user is a member of group X), but hide otherwise".

For this, I'm constantly looking up the IDs of the various levels and it just dawned on me that this is terribly inefficient.

To get around this, I tried declaring variables at the top of my functions.php, i.e. $gold_member = 4122;.

I'm a bit of a beginner in php and tried then passing those variables into my functions via global $gold_member;. But that didn't work and I also read somewhere that it is considered bad form to use globals.

Is there any standard way of solving this problem? Basically what I'm after is something very similar to how variables are used in SASS or LESS. I want to define them once and then use them in functions.php and in the templates.

  • 3
    Can't you use WordPress roles for this, i.e. make a gold_member role to assign users to?
    – Rup
    May 21, 2017 at 9:18
  • There is an excellent answer here: stackoverflow.com/a/10963049/2073994
    – Laxmana
    May 21, 2017 at 9:30
  • 1
    Use user roles and capabilitis to control what a user can do, including access to content. I think your question is wrong, like an XY problem.
    – cybmeta
    May 21, 2017 at 10:22

1 Answer 1


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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.