2

I need to show some info only to admins visiting a page, so I need a conditional tag to identify them. So far I have found:

<?php if ( current_user_can('manage_options') ): ?>

is this the correct function?

1
  • Perfectly fine to check that way, you're better of checking against a cap than a role, because users may change the existing roles, or names... capabilities like manage_options won't necessarily change, because a role will need that cap to set things such as the site_url.. I'd personally opt for using what you have posted..
    – t31os
    Nov 18, 2010 at 12:46

2 Answers 2

6

Yes, that's good.

You can be a little safer using <?php if(current_user_can('manage_plugins') ); ?>

2
  • How exactly is that any safer?
    – t31os
    Nov 18, 2010 at 12:45
  • By 'safer' all I meant was that it's a much better capability check than the one for options. In case you build custom roles etc, I feel that managing plugins is the last possible permission that you would want to give someone without making him an admin. Nov 19, 2010 at 9:07
6

I think it is better to check for role rather than specific capability for such purpose, this should work:

<?php if ( current_user_can('administrator') ): ?>

See Roles and Capabilities in Codex.

4
  • Capabilities are more reliable because users might change their roles around, caps are pretty much guaranteed to work (core code expects caps, not roles).. it's good to follow suit..
    – t31os
    Nov 18, 2010 at 16:02
  • Well, what if capabilities get re-arranged by user? As for me if you want administrator then you check for it, not for what administrator might or might not be able to do. Imagine encountering these in code... What is more clear - check for administrator or for some cap you have to lookup? Not sure what you mean by core code expects. This functions is documented to works with roles as well as capabilities.
    – Rarst
    Nov 18, 2010 at 16:21
  • WordPress has current_user_can checks throughout core against caps, the user is not ever in a position to remove those caps because they'll break functionality within WordPress, Roles however can be changed without breaking those capability checks. It may be documented to work with caps, but that's never been an intended use(or at least a couple of devs have suggested as much in role/cap related trac tickets). One reference for related discussion, see: core.trac.wordpress.org/ticket/14387
    – t31os
    Nov 18, 2010 at 17:00
  • 1
    FROM codex.wordpress.org/Function_Reference/current_user_can Do not pass a role name to current_user_can(), as this is not guaranteed to work correctly (see #22624).
    – sakibmoon
    Feb 23, 2014 at 4:29

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.