add_role()
云策文档标注
概述
add_role() 函数用于在 WordPress 中添加一个新角色,仅当该角色不存在时生效。它接受角色名称、显示名称和权限数组作为参数,并返回 WP_Role 对象或 void。
关键要点
- 函数签名:add_role( $role, $display_name, $capabilities = array() ),其中 $role 和 $display_name 为必填字符串,$capabilities 为可选数组。
- 权限数组可以是以数字索引的字符串数组,或是以权限名为键、布尔值为值的关联数组,false 值用于显式拒绝权限。
- 如果角色已存在,函数不会更新数据库,直接返回 null,避免重复操作。
- 最佳实践是在插件激活钩子(如 register_activation_hook)或条件块中调用,以减少数据库负载。
- 要修改现有角色的权限,需先使用 remove_role() 删除角色,再调用 add_role() 重新添加。
- 从 WordPress 6.9.0 开始,支持以数字索引数组形式传递权限字符串。
代码示例
// 添加一个可编辑文章的角色
add_role( 'custom_role', 'Custom Role', array(
'read',
'edit_posts',
) );
// 使用关联数组添加角色,明确拒绝删除文章权限
add_role( 'custom_role', 'Custom Role', array(
'read' => true,
'edit_posts' => true,
'delete_posts' => false,
) );
// 基于现有角色创建新角色
add_role( 'superintendent', 'Superintendent', get_role( 'administrator' )->capabilities );注意事项
- 确保在全局 $wp_roles 可用后调用此函数,例如在 'init' 钩子中,特别是在 mu-plugins 上下文中。
- 避免在每次页面加载时执行,以防止不必要的数据库更新。
- 函数返回 WP_Role 对象(成功时)或 null(角色已存在时),可用于检查操作结果。
原文内容
Adds a role, if it does not exist.
Description
The list of capabilities can be passed either as a numerically indexed array of capability names, or an associative array of boolean values keyed by the capability name. To explicitly deny the role a capability, set the value for that capability to false.
Examples:
// Add a role that can edit posts.
add_role( 'custom_role', 'Custom Role', array(
'read',
'edit_posts',
) );
Or, using an associative array:
// Add a role that can edit posts but explicitly cannot not delete them.
add_role( 'custom_role', 'Custom Role', array(
'read' => true,
'edit_posts' => true,
'delete_posts' => false,
) );
Parameters
$rolestringrequired-
Role name.
$display_namestringrequired-
Display name for role.
$capabilitiesarray|arrayoptional-
Capabilities to be added to the role.
Default:
array()
Source
function add_role( $role, $display_name, $capabilities = array() ) {
if ( empty( $role ) ) {
return;
}
return wp_roles()->add_role( $role, $display_name, $capabilities );
}
Skip to note 9 content
Roger Theriault
Be sure to use this function (and similar role functions) only in an activation hook or within a conditional block. There is no need for this to execute every time the page loads, and it will keep updating the database every time it’s called.
For example, this will store an option to track the version of the custom roles and will only update the database once:
function xx__update_custom_roles() { if ( get_option( 'custom_roles_version' ) < 1 ) { add_role( 'custom_role', 'Custom Subscriber', array( 'read' => true, 'level_0' => true ) ); update_option( 'custom_roles_version', 1 ); } } add_action( 'init', 'xx__update_custom_roles' );Skip to note 10 content
Jules Colle
You can also easily create a new user role based on an existing user role.
( equivalent to WP CLI:
wp role create <role-key> <role-name> --clone=<role>)Example: create a role Superintended with the same capabilities as Administrator
add_role( 'superintendent', 'Superintendent', get_role( 'administrator' )->capabilities );Skip to note 11 content
samjco
A list of all possible Capabilities per user roles:
https://wordpress.org/support/article/roles-and-capabilities/#capability-vs-role-table
Super Admin
=========================
create_sites
delete_sites
manage_network
manage_sites
manage_network_users
manage_network_plugins
manage_network_themes
manage_network_options
upload_plugins
upload_themes
upgrade_network
setup_network
Super Admin + Administrator
==========================================
activate_plugins (single site or enabled by network setting)
create_users (single site)
delete_plugins (single site)
delete_themes (single site)
delete_users (single site)
edit_files (single site)
edit_plugins (single site)
edit_theme_options
edit_themes (single site)
edit_users (single site)
export
import
Super Admin + Administrator
=============================================
install_plugins (single site)
install_themes (single site)
list_users
manage_options
promote_users
remove_users
switch_themes
update_core (single site)
update_plugins (single site)
update_themes (single site)
edit_dashboard
customize
delete_site
Super Admin + Administrator + Editor
====================================================
moderate_comments
manage_categories
manage_links
edit_others_posts
edit_pages
edit_others_pages
edit_published_pages
publish_pages
delete_pages
delete_others_pages
delete_published_pages
delete_others_posts
delete_private_posts
edit_private_posts
read_private_posts
delete_private_pages
edit_private_pages
read_private_pages
unfiltered_html (single site)
unfiltered_html
Super Admin + Administrator + Editor + Author
==========================================================
edit_published_posts
upload_files
publish_posts
delete_published_posts
Super Admin + Administrator + Editor + Author + Contributor
========================================================================
edit_posts
delete_posts
Super Admin + Administrator + Editor + Author + Contributor + Subscriber
======================================================================================
read
Skip to note 12 content
Codex
Create a new role when a plugin is activated
See
register_activation_hook.function add_roles_on_plugin_activation() { add_role( 'custom_role', 'Custom Subscriber', array( 'read' => true, 'level_0' => true ) ); } register_activation_hook( __FILE__, 'add_roles_on_plugin_activation' );Skip to note 13 content
Codex
Note: Delete existing role
You can not change the capabilities of an existing role using
add_role(). This function will stop executing and returnnullis the specified role name already exists.You can change a user role’s capabilities (or display name) by using
remove_role(), thenadd_role().This is for development only. Once you have nailed down your list of capabilities, there’s no need to keep the remove_role() code.
Skip to note 14 content
Codex
Example
Create a new “Guest Author” role.
$result = add_role( 'guest_author', __( 'Guest Author', 'testdomain' ), array( 'read' => true, // true allows this capability 'edit_posts' => true, 'delete_posts' => false, // Use false to explicitly deny ) ); if ( null !== $result ) { echo "Success: {$result->name} user role created."; } else { echo 'Failure: user role already exists.'; }Skip to note 15 content
Codex
Usage
Skip to note 16 content
Codex
Note: When to call
Make sure the global
$wp_rolesis available before attempting to add or modify a role. The best practice is to use a plugin (or theme) activation hook to make changes to roles (since you only want to do it once!).mu-pluginsloads too early, so use an action hook (like'init') to wrap youradd_role()call if you’re doing this in the context of an mu-plugin.