WordPress.org

Ready to get started?Download WordPress

Forums

Plugin author: Having problems with capabilities (4 posts)

  1. shiv379
    Member
    Posted 6 years ago #

    Hi all!
    I'm writing my first plugin and I am trying to add in capabilities so the functionality can be restricted to certain roles, however no matter where I put the line:
    if ( $user->has_cap('edit_resource_links') )
    it breaks the plugin!

    I'd also like to know if there's a quick way to remove all capabilities matching a certain name from *every role*, as a cleanup exercise. Is this possible without looping through all roles manually?

    Does anyone know any good tutes on using capabilities in plugins? I've had a look around but the documentation on this is sparse!

    ~Shiv

  2. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    Define what you mean by "breaks the plugin". What, exactly, does it do?

    Also, is $user defined? How did you get the $user variable?

    If you want to remove a cap from all the users, you have to go through all the users and call remove_cap on each of them. You'd do that sorta like this:

    $users = get_users_of_blog();
    foreach ($users as $user) {
    $wpuser = new WP_User($user->user_id);
    $wpuser->remove_cap('whatever_cap');
    }

    Or maybe you wanted to remove all of a given users capabilities entirely? That would be easier:

    $wpuser = new WP_User($some_user_id);
    $wpuser->remove_all_caps();
  3. shiv379
    Member
    Posted 6 years ago #

    Thanks for the reply :)

    I had thought that $user was a global variable defined by WP for the current user, I'm guessing that's not the case?
    By breaks the plugin I mean the php chokes and the page doesn't load. I'm guessing now that that's because of the $user issue tho. What's the best way to check if the current user has a cap?

    Thanks for your advice on the loop to remove the cap from all users, I'll give that a go!

    ~Shiv

  4. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    Nope, $user is not a global.

    If you want to operate on the current user, you can do this:

    $user = wp_get_current_user();
    $user->do_whatever();

    And then you can do stuff like I showed above.

Topic Closed

This topic has been closed to new replies.

About this Topic