4

I am filtering the map_meta_cap() function, which is called from $user->has_cap (which is called from current_user_can()). I only want my filter to execute if the current user is an administrator, so I need a conditional in my filter that checks their role.

I can't use current_user_can(), because that invokes my filter, causing an infinite loop.

Is there a reliable way to check whether someone is an administrator without using current_user_can() ?

  • Might want to look at the $current_user global, remembering to add global scope when inside a function.. – t31os Jan 26 '11 at 20:28
  • thanks. i have seen a few ways i could check the user role from that object, but wasn't sure how reliable they were... might use in_array('administrator', $current_user->roles) ? – jessica Jan 26 '11 at 20:33
  • As long as you perform that logic late enough(ie. on/after init) it should be fine.. :) – t31os Jan 26 '11 at 22:14
  • Have done, though i've re-examined my previous thoughts, see answer... :) – t31os Jan 27 '11 at 0:53
5

You could check the $current_user variable to determine the role.

I believe it should be realiable after init(maybe even on init) for a logged in user, a guest visitor obviously won't have any data associated with him or her yet(so it'll be empty/unset).

You can also call up get_currentuserinfo() to populate the $current_user var, but i've personally never found a need when calling $current_user after init(but i'm sure there may be cases when you need to call it, so it's linked below for reference).

http://codex.wordpress.org/Function_Reference/get_currentuserinfo

  • sweet, i will check if $current_user->roles is empty, and if so, use get_currentuserinfo(). Thanks again! – jessica Jan 27 '11 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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