国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Key Points
Back to the scenes mechanism
Role storage
Use permissions in core code
Using roles and permissions: WordPress API
Access API
current_user_can()
WP_User::has_cap
get_editable_roles()
get_role()
WP_Role::has_cap()
Custom API
add_role()
remove_role()
WP_Role::add_cap()
WP_Role::remove_cap()
WP_User::add_role()
WP_User::remove_role()
WP_User::add_cap()
WP_User::remove_cap()
Some issues with WordPress API
function to trigger code when the plugin is enabled in the backend.
Conclusion
Frequently Asked Questions about Mastering WordPress Roles and Permissions
What is the default user role in WordPress? What are their permissions?
How to add new user roles in WordPress?
How to delete user roles in WordPress?
How to add permissions to user roles in WordPress?
How to remove permissions from user roles in WordPress?
How to change the default user role in WordPress?
How to assign multiple roles to users in WordPress?
How to limit content access based on user roles in WordPress?
How to create custom permissions in WordPress?
How to check if a user in WordPress has specific permissions?
Home CMS Tutorial WordPress Mastering WordPress Roles and Capabilities

Mastering WordPress Roles and Capabilities

Feb 16, 2025 am 11:49 AM

WordPress User Management: In-depth Analysis of Roles and Permissions

WordPress's user management system is based on roles and permissions. A role is an entity that contains a unique name and a set of permissions, each of which defines the level of access to platform-specific features of that role. Let's dig into the working mechanisms of WordPress roles and permissions.

Key Points

  • WordPress's user management is based on roles and permissions. A role has a unique name and a set of permissions that define the level of access to different features of the platform by a role.
  • WordPress provides a comprehensive API to customize roles and their permissions. Functions such as add_role(), remove_role(), add_cap(), and remove_cap() can be used to manage roles and permissions. However, you must pay attention to database access and performance when using these functions.
  • There are several ways to avoid database issues when dealing with roles and permissions. One way is to trigger the code only when the plugin is enabled, you can use the register_activation_hook() function. Another way is to bypass the WordPress database by setting the $wp_user_roles global variable.

Back to the scenes mechanism

Role storage

The default role and permission list is available on WordPress Codex.

The

database stores this list in the wp_options table.

It uses the serialized wp_user_roles key.

Mastering WordPress Roles and Capabilities The deserialized data is as follows:

<code>array(
    'administrator' => array(
        'name'         => '管理員',
        'capabilities' => array(
            'switch_themes'          => true,
            'edit_themes'            => true,
            'activate_plugins'       => true,
            'edit_plugins'           => true,
            'edit_users'             => true,
            // [...]
        )
    ),
    'contributor' => array(
        'name'         => '投稿者',
        'capabilities' => array(
            'delete_pages'           => true,
            'delete_others_pages'    => true,
            'delete_published_pages' => true,
            'delete_posts'           => true,
            // [...]
        )
    ),
    // [...]
);</code>

This metadata is automatically set when a new WordPress site is installed.

When WordPress starts, the

class loads the list from the database. WP_Roles

This happens between

and plugins_loaded hooks. init

Link user to role

WordPress uses

stored in the wp_usermeta table to link users to their roles. meta_key

After deserialization, the metadata is as follows: Mastering WordPress Roles and Capabilities

<code>array(
    'administrator' => true
)</code>
Note that WordPress uses arrays, although users can only have one role at a time, we will see why later.

Also, remember

is the prefix of the current blog. wp_

(We can get it using the

function). $GLOBALS['wpdb']->get_blog_prefix()

In a multi-site installation, this allows users to use different roles in different instances:

  • => wp_capabilitiesa:1:{s:13:"administrator";b:1;}
  • => wp_10_capabilitiesa:1:{s:11:"contributor";b:1;}
  • => wp_15_capabilitiesa:1:{s:10:"subscriber";b:1;}
  • [...]
This rule also applies to the

entry we saw in the wp_options table. wp_user_roles

Finally, we can see the wp_user_level metadata as well as the role.

It is used to deal with characters in older versions of WordPress and is now deprecated.

Use permissions in core code

We have learned how roles are loaded and linked to users; from there, WordPress is able to get permissions for a given user when needed.

Some default permissions are hardcoded in WordPress core code.

For example, when the plugin screen is loaded, it will check if the current user can manage the plugin by running the following code:

<code>array(
    'administrator' => array(
        'name'         => '管理員',
        'capabilities' => array(
            'switch_themes'          => true,
            'edit_themes'            => true,
            'activate_plugins'       => true,
            'edit_plugins'           => true,
            'edit_users'             => true,
            // [...]
        )
    ),
    'contributor' => array(
        'name'         => '投稿者',
        'capabilities' => array(
            'delete_pages'           => true,
            'delete_others_pages'    => true,
            'delete_published_pages' => true,
            'delete_posts'           => true,
            // [...]
        )
    ),
    // [...]
);</code>

Roles are never hardcoded; roles are just permission wrappers, which only exist in the database.

Using roles and permissions: WordPress API

Access API

WordPress provides the following global functions to help us handle roles.

current_user_can()

Check whether the current user has the required permissions.

<code>array(
    'administrator' => true
)</code>

WP_User::has_cap

Check whether a specific user has permission.

<code>if (!current_user_can('activate_plugins'))
{
    wp_die(__('您沒有足夠的權限來管理此站點的插件。'));
}</code>

We can notice that current_user_can uses this function.

get_editable_roles()

Returns to editable roles.

<code>add_action('init', function()
{
    if (current_user_can('install_plugins'))
    {
        echo '您可以安裝插件';
    }
    else
    {
        echo '您不能安裝插件';
    }
});</code>

This list may be overwritten by editable_roles filters, so we should not rely on this function to get the full list of roles on the website.

Please note the use of the admin_init hook, because the function has not been loaded in the init hook yet.

get_role()

Get WP_Role object based on its slug.

<code>add_action('init', function()   
{
    $user = get_user_by('slug', 'admin');
    if ($user->has_cap('install_plugins'))
    {
        echo '管理員可以安裝插件';
    }
    else
    {
        echo '管理員不能安裝插件';
    }
});</code>

WP_Role::has_cap()

Check whether the role has the required permissions.

<code>add_action('admin_init', function()
{
    $roles = get_editable_roles();
    var_dump($roles);
});</code>

Custom API

WordPress also provides a complete API to customize roles and their permissions.

add_role()

Register a new role in the database.

<code>add_action('init', function()
{
    $role = get_role('administrator');
    var_dump($role);
});

// 這將打?。?// WP_Role 對象
// (
//     [name] => administrator
//     [capabilities] => Array
//         (
//             [switch_themes] => 1
//             [edit_themes] => 1
//             [activate_plugins] => 1
//             [edit_plugins] => 1
//             [...]</code>

remove_role()

If present, delete the required role from the database.

<code>add_action('init', function()
{
    $role = get_role('administrator');
    var_dump($role->has_cap('install_plugins')); // 打印 TRUE
});</code>

WP_Role::add_cap()

Add permissions to the role.

<code>add_action('init', function()
{
    add_role('plugins_manager', '插件管理員', array(
        'install_plugins',
        'activate_plugins',
        'edit_plugins'
    ));
});</code>

This can be core permissions (install_plugins, edit_posts…) or any custom string (my_awesome_plugin_cap).

It allows us to register as many custom permissions as possible for our plugin.

WP_Role::remove_cap()

If it exists, delete permissions from the role.

<code>add_action('init', function()
{
    remove_role('plugins_manager');
});</code>

WP_User::add_role()

Add roles to a given user.

<code>add_action('init', function()
{
    $role = get_role('contributor');
    $role->add_cap('install_plugins');
});</code>

This function allows you to theoretically set multiple roles for the same user.

Since the WordPress backend only displays and manages one role per user, we should not add multiple roles for users and should always use WP_User::remove_role() before adding a new role.

WP_User::remove_role()

Remove roles from the given user.

<code>add_action('init', function()
{
    $role = get_role('contributor');
    $role->remove_cap('install_plugins');
});</code>

WP_User::add_cap()

Add permissions to a given user.

<code>array(
    'administrator' => array(
        'name'         => '管理員',
        'capabilities' => array(
            'switch_themes'          => true,
            'edit_themes'            => true,
            'activate_plugins'       => true,
            'edit_plugins'           => true,
            'edit_users'             => true,
            // [...]
        )
    ),
    'contributor' => array(
        'name'         => '投稿者',
        'capabilities' => array(
            'delete_pages'           => true,
            'delete_others_pages'    => true,
            'delete_published_pages' => true,
            'delete_posts'           => true,
            // [...]
        )
    ),
    // [...]
);</code>

Mastering WordPress Roles and Capabilities This is very useful if we want to add a single permission to the user without having to create a full role.

WP_User::remove_cap()

Remove permissions from the given user.

<code>array(
    'administrator' => true
)</code>

Some issues with WordPress API

Apart from one question, the functions we see look good: database access and performance.

What we mainly focus on when dealing with roles and permissions is when should our code be triggered?

To explain this, let's take a look at WordPress core code.

First, we want to add a new empty character:

<code>if (!current_user_can('activate_plugins'))
{
    wp_die(__('您沒有足夠的權限來管理此站點的插件。'));
}</code>
The following are the first few lines of the

function (actually redirected to add_role): WP_Roles::add_role

<code>add_action('init', function()
{
    if (current_user_can('install_plugins'))
    {
        echo '您可以安裝插件';
    }
    else
    {
        echo '您不能安裝插件';
    }
});</code>
If we add a new role, the

function runs once and then does nothing. add_role

Next, suppose we want to add permissions to our newly created role:

<code>add_action('init', function()   
{
    $user = get_user_by('slug', 'admin');
    if ($user->has_cap('install_plugins'))
    {
        echo '管理員可以安裝插件';
    }
    else
    {
        echo '管理員不能安裝插件';
    }
});</code>
The

function in WordPress 4.2.2 is as follows: WP_Role::add_cap()

<code>add_action('admin_init', function()
{
    $roles = get_editable_roles();
    var_dump($roles);
});</code>
It updates the

object, but we can also see that the database will update every time our code runs, even if our new permissions are already registered! $this->roles This means that if we care about performance, all the code we write for custom roles and permissions should not run when each page is loading.

Solution

There are several ways to avoid these database problems.

Activate with plug-in

WordPress allows plugin authors to use the

function to trigger code when the plugin is enabled in the backend.

Let's create a sample plugin: register_activation_hook()

This code will only run once when the plugin is enabled on the website.

<code>add_action('init', function()
{
    $role = get_role('administrator');
    var_dump($role);
});

// 這將打?。?// WP_Role 對象
// (
//     [name] => administrator
//     [capabilities] => Array
//         (
//             [switch_themes] => 1
//             [edit_themes] => 1
//             [activate_plugins] => 1
//             [edit_plugins] => 1
//             [...]</code>
Now, we must remember that this solution depends on the activation and deactivation of the plugin.

What happens if the plugin is already in production, or if the reactivate is omitted when the update is pushed?

In fact, this solution also relies on the database and requires an extra step when pushing the code.

Bypass WordPress database

There is also an undisclosed solution that works well in some cases.

Let's look at the WordPress core code at the end, when the

object loads the role from the database when WordPress starts:

WP_RolesWordPress checks for the

global variables before getting data from the database.
<code>add_action('init', function()
{
    $role = get_role('administrator');
    var_dump($role->has_cap('install_plugins')); // 打印 TRUE
});</code>

If set, WordPress will use its contents and block the database usage by setting the $wp_user_roles variable to false.

Let's try it out, keeping only a new, restricted administrator role: $this->use_db

When loading the backend, we can see that it retains the definition of our custom role:

Mastering WordPress Roles and Capabilities This solution solves the database problem, but may introduce some other issues:

  • Plugins using native APIs may not work properly.
  • We have to manually set the definition of each role, even for the role we don't want to change.

However, this may be a viable solution when building a custom WordPress application that requires a custom list of static roles:

  • Role definitions can be versioned with the code.
  • Pusing new code to the environment will automatically update the definition.
  • No need to consider database issues anymore.

Conclusion

In this article, I introduce an overview of roles and permissions usage in WordPress.

Although its complete API allows us to do almost anything we want, relationships with databases are still the main problem.

We must keep this in mind when developing our plugins and themes.

What do you think about the way WordPress manages roles? Looking forward to your feedback!

Frequently Asked Questions about Mastering WordPress Roles and Permissions

What is the default user role in WordPress? What are their permissions?

WordPress has six default user roles: Super Administrator, Administrator, Editor, Author, Contributor, and Subscriber. Each role has a specific set of permissions. For example, a super administrator can access all administrative features of multiple sites. Administrators can perform all administrative tasks on a single site. Editors can publish and manage posts, including those of other users. Authors can post and manage their own posts. Contributors can write and manage their own posts, but they cannot be posted. Subscribers can only manage their profile.

How to add new user roles in WordPress?

To add a new user role in WordPress, you can use the add_role() function. This function accepts three parameters: role, display name, and permission array. For example, to add a new role called "custom_role" and have permission to read and edit posts, you can use the following code:

add_role( 'custom_role', __('自定義角色'), array( 'read' => true, // 可以讀取帖子 'edit_posts' => true, // 可以編輯帖子 ) );

How to delete user roles in WordPress?

To delete a user role in WordPress, you can use the remove_role() function. This function accepts one parameter: role. For example, to delete the previously added "custom_role", you can use the following code:

remove_role('custom_role');

How to add permissions to user roles in WordPress?

To add permissions to user roles in WordPress, you can use the add_cap() function. This function accepts two parameters: permission and a Boolean value indicating whether the role has the permission. For example, to add "publish_posts" permission to "custom_role", you can use the following code:

$role = get_role('custom_role'); $role->add_cap('publish_posts', true);

How to remove permissions from user roles in WordPress?

To remove permissions from user roles in WordPress, you can use the remove_cap() function. This function accepts a parameter: permission. For example, to remove the "publish_posts" permission from "custom_role", you can use the following code:

$role = get_role('custom_role'); $role->remove_cap('publish_posts');

How to change the default user role in WordPress?

To change the default user role in WordPress, navigate to Settings > General in the WordPress dashboard. Under New User Default Roles, select the role you want to set as default from the drop-down menu.

How to assign multiple roles to users in WordPress?

WordPress does not support assigning multiple roles to users by default. However, you can do this using plugins like Multiple Roles. After you install and activate the plugin, you can assign multiple roles to the user from the user's profile page.

How to limit content access based on user roles in WordPress?

To restrict content access based on user roles in WordPress, you can use plugins like Members. This plugin allows you to control which roles can access specific content on your website.

How to create custom permissions in WordPress?

To create custom permissions in WordPress, you can use the add_cap() function. This function accepts two parameters: permission and a Boolean value indicating whether the role has the permission. For example, to add a custom permission named "manage_custom" to "custom_role", you can use the following code:

$role = get_role('custom_role'); $role->add_cap('manage_custom', true);

How to check if a user in WordPress has specific permissions?

To check if a user in WordPress has specific permissions, you can use the current_user_can() function. This function accepts a parameter: permission. For example, to check if the current user has "manage_custom" permission, you can use the following code:

if (current_user_can('manage_custom')) { // 當前用戶具有“manage_custom”權限 }

All pictures retain their original format and location.

The above is the detailed content of Mastering WordPress Roles and Capabilities. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use the WordPress testing environment How to use the WordPress testing environment Jun 24, 2025 pm 05:13 PM

Use WordPress testing environments to ensure the security and compatibility of new features, plug-ins or themes before they are officially launched, and avoid affecting real websites. The steps to build a test environment include: downloading and installing local server software (such as LocalWP, XAMPP), creating a site, setting up a database and administrator account, installing themes and plug-ins for testing; the method of copying a formal website to a test environment is to export the site through the plug-in, import the test environment and replace the domain name; when using it, you should pay attention to not using real user data, regularly cleaning useless data, backing up the test status, resetting the environment in time, and unifying the team configuration to reduce differences.

How to use Git with WordPress How to use Git with WordPress Jun 26, 2025 am 12:23 AM

When managing WordPress projects with Git, you should only include themes, custom plugins, and configuration files in version control; set up .gitignore files to ignore upload directories, caches, and sensitive configurations; use webhooks or CI tools to achieve automatic deployment and pay attention to database processing; use two-branch policies (main/develop) for collaborative development. Doing so can avoid conflicts, ensure security, and improve collaboration and deployment efficiency.

How to create a simple Gutenberg block How to create a simple Gutenberg block Jun 28, 2025 am 12:13 AM

The key to creating a Gutenberg block is to understand its basic structure and correctly connect front and back end resources. 1. Prepare the development environment: install local WordPress, Node.js and @wordpress/scripts; 2. Use PHP to register blocks and define the editing and display logic of blocks with JavaScript; 3. Build JS files through npm to make changes take effect; 4. Check whether the path and icons are correct when encountering problems or use real-time listening to build to avoid repeated manual compilation. Following these steps, a simple Gutenberg block can be implemented step by step.

How to set up redirects in WordPress htaccess How to set up redirects in WordPress htaccess Jun 25, 2025 am 12:19 AM

TosetupredirectsinWordPressusingthe.htaccessfile,locatethefileinyoursite’srootdirectoryandaddredirectrulesabovethe#BEGINWordPresssection.Forbasic301redirects,usetheformatRedirect301/old-pagehttps://example.com/new-page.Forpattern-basedredirects,enabl

How to flush rewrite rules programmatically How to flush rewrite rules programmatically Jun 27, 2025 am 12:21 AM

In WordPress, when adding a custom article type or modifying the fixed link structure, you need to manually refresh the rewrite rules. At this time, you can call the flush_rewrite_rules() function through the code to implement it. 1. This function can be added to the theme or plug-in activation hook to automatically refresh; 2. Execute only once when necessary, such as adding CPT, taxonomy or modifying the link structure; 3. Avoid frequent calls to avoid affecting performance; 4. In a multi-site environment, refresh each site separately as appropriate; 5. Some hosting environments may restrict the storage of rules. In addition, clicking Save to access the "Settings>Pinned Links" page can also trigger refresh, suitable for non-automated scenarios.

How to send email from WordPress using SMTP How to send email from WordPress using SMTP Jun 27, 2025 am 12:30 AM

UsingSMTPforWordPressemailsimprovesdeliverabilityandreliabilitycomparedtothedefaultPHPmail()function.1.SMTPauthenticateswithyouremailserver,reducingspamplacement.2.SomehostsdisablePHPmail(),makingSMTPnecessary.3.SetupiseasywithpluginslikeWPMailSMTPby

How to integrate third-party APIs with WordPress How to integrate third-party APIs with WordPress Jun 29, 2025 am 12:03 AM

Tointegratethird-partyAPIsintoWordPress,followthesesteps:1.SelectasuitableAPIandobtaincredentialslikeAPIkeysorOAuthtokensbyregisteringandkeepingthemsecure.2.Choosebetweenpluginsforsimplicityorcustomcodeusingfunctionslikewp_remote_get()forflexibility.

How to make a WordPress theme responsive How to make a WordPress theme responsive Jun 28, 2025 am 12:14 AM

To implement responsive WordPress theme design, first, use HTML5 and mobile-first Meta tags, add viewport settings in header.php to ensure that the mobile terminal is displayed correctly, and organize the layout with HTML5 structure tags; second, use CSS media query to achieve style adaptation under different screen widths, write styles according to the mobile-first principle, and commonly used breakpoints include 480px, 768px and 1024px; third, elastically process pictures and layouts, set max-width:100% for the picture and use Flexbox or Grid layout instead of fixed width; finally, fully test through browser developer tools and real devices, optimize loading performance, and ensure response

See all articles