WordPress Function to New Roles and Capabilities – Only run once!
New Roles and Capabilities – Only run once!
I keep these handy, this is the right way to do them without a plugin. They set a single field (prefix_user_roles) in the options database, and you don’t need a plugin to set them. Refer to the Codex page for a list of what capabilities are available and descriptions for what they do. You only need to uncomment one of these blocks, load any page and then comment them again! Here I’m creating a role that’s got the capabilities I need:
/* Capabilities */ // To add the new role, using 'international' as the short name and // 'International Blogger' as the displayed name in the User list and edit page: /* add_role('international', 'International Blogger', array( 'read' => true, // True allows that capability, False specifically removes it. 'edit_posts' => true, 'delete_posts' => true, 'edit_published_posts' => true, 'publish_posts' => true, 'edit_files' => true, 'import' => true, 'upload_files' => true //last in array needs no comma! )); */ // To remove one outright or remove one of the defaults: /* remove_role('international'); */
It’s sometimes handy to add/remove from an existing role rather than removing and re-adding one. Again, you only need to uncomment it, reload a page and then comment it again. This will store the role/capability properly in the options table. (This allows you, the developer to control them and removes the overhead of the bulky plugins that do the same thing.) Here I’m changing the author role to delete their published posts (the default), but allowing them the capability to edit their published posts (which isn’t possible for this role by default)– using *add_cap* or *remove_cap*.
/* $edit_role = get_role('author'); $edit_role->add_cap('edit_published_posts'); $edit_role->remove_cap('delete_published_posts'); */
I keep a spreadsheet with the grid from the Codex page for sites that modify this way, so I can remember how things are set, though leaving the commented out code in your functions.php file will work to. Don’t leave these examples uncommented, or it will write to the database with each page load!