0
0
Wordpressframework~5 mins

User roles and permissions in Wordpress

Choose your learning style9 modes available
Introduction

User roles and permissions help control what different users can do on a WordPress site. This keeps the site safe and organized.

When you want to let someone write posts but not change site settings.
When you need to give a trusted person full control over the site.
When you want to allow users to comment but not publish content.
When you want to restrict access to certain parts of the admin dashboard.
When you want to add custom roles for special tasks on your site.
Syntax
Wordpress
<?php
// Add a new role
add_role('custom_role', 'Custom Role', [
  'read' => true,
  'edit_posts' => true,
  'delete_posts' => false
]);

// Check if user has a capability
if (current_user_can('edit_posts')) {
  // User can edit posts
}

// Remove a role
remove_role('custom_role');
?>

Roles group capabilities (permissions) for easier management.

Use current_user_can() to check permissions before actions.

Examples
This creates a new role that can edit and publish posts and moderate comments.
Wordpress
<?php
// Add an Editor role with extra capability
add_role('custom_editor', 'Custom Editor', [
  'read' => true,
  'edit_posts' => true,
  'publish_posts' => true,
  'moderate_comments' => true
]);
?>
This checks the current user's permission and shows a message accordingly.
Wordpress
<?php
// Check if current user can delete posts
if (current_user_can('delete_posts')) {
  echo 'You can delete posts.';
} else {
  echo 'You cannot delete posts.';
}
?>
This deletes the custom role from the site.
Wordpress
<?php
// Remove a custom role
remove_role('custom_editor');
?>
Sample Program

This code adds a new role with specific permissions, checks if the current user can publish posts, prints a message, and then removes the role.

Wordpress
<?php
// Add a new role called 'content_manager'
add_role('content_manager', 'Content Manager', [
  'read' => true,
  'edit_posts' => true,
  'publish_posts' => true,
  'delete_posts' => false
]);

// Check if current user can publish posts
if (current_user_can('publish_posts')) {
  echo 'You can publish posts.';
} else {
  echo 'You cannot publish posts.';
}

// Remove the role after use
remove_role('content_manager');
?>
OutputSuccess
Important Notes

Roles and permissions are stored in the database and persist until changed.

Be careful when removing roles; users assigned to that role lose those permissions.

Always check permissions before allowing sensitive actions to keep your site secure.

Summary

User roles group permissions to control what users can do.

Use add_role() to create roles and remove_role() to delete them.

Check permissions with current_user_can() before performing actions.