Add New Role in WordPress Programmatically

Wanted:

I want to make two role:

  • student with only read capability
  • teacher with read, delete_posts, edit_posts, publish_posts and upload_files capability

Question:

How to make that two role with php code inside plugin  … ?

Reply:

Insert below code into your plugin-filename:

function nambahUserRole(){

add_role(

‘teacher’,
‘Teacher’,

array(

‘read’ => true,
‘delete_posts’ => true,
‘edit_posts’ => true,
‘publish_posts’ => true,
‘upload_files’ => true

)

);

add_role(
‘student’,
‘Student’,

array(

‘read’ => true

)

);

}

register_activation_hook( __FILE__, ‘nambahUserRole’ );

Explain:

  • add_role( $name, $display_name, $capabilities) is a function to add a new role
  • The Example role and all capabilities can be see in https://wordpress.org/support/article/roles-and-capabilities/
  • register_activation_hook() is used to making role when plugin activated

Result:

role

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *