wordpress custom role capabilities

Posted on March 24, 2015 by Suresh Kamrushi in PHP

Besides default capabilities in wordpress, we can set additional capabilities for our custom plugins or custom pages.
Setting custom role capabilities in wordpress for custom plugin is as below:
Add following line in your plugin file (suppose you have created a test plugin with folder name as “test_plugin” than put the following lines in “test_plugin.php” file:

function add_new_capability() {           
    $role = get_role('contributer');   //getting role object. it can be "subscriber" or "author"
    $role->add_cap( 'manage_appointment' );   // pushing new capabilities.

function addAppointments_menu() {    
    if(current_user_can("manage_appointment")) {
         'ManageAppointments', // The title to be displayed on the corresponding page for this menu
         'Appointments', // The text to be displayed for this actual menu item  
         'manage_appointment', 	// Which type of users can see this menu  
         'test-appointments-plugin', // The unique ID - that is, the slug - for this menu item  
         'manage_appointments', // The name of the function to call when rendering the menu for this page
         plugins_url('images/icon-cal.gif', __FILE__ ));   // Icon for the Main menu in Admin panel            	
function manage_appointments() {
    //Your page content goes here
add_action( 'admin_menu', 'addAppointments_menu' );

Code is as per WordPress version: 3.9.1

More information about different function used:
1) current_user_can() : Function checks whether the current user has a certain capability or not.
2) add_menu_page() : This function creates a new top level menu section in the admin menu sidebar.
3) add_action() : Function is used to add extra submenus and menu options to the admin panel’s menu structure.
4) get_role() : Function get a role definition. It returns object.
5) add_submenu_page() :This function takes a capability which will be used to determine whether or not a page is included in the menu.

Tagged as