问题
在调用$author->remove_cap($cap) 后,作者角色中的功能被删除,不仅在内存中,而且在数据库中(有关实现和链接,请参见下面的参考部分)。因此,移除对 set_capabilities() 的调用或向角色添加新用户不会重置角色功能。
解决方案
方法 1 - 使用 Wordpress
您可以执行与 set_capabilities() 相反的操作,例如 add_capabilities(),如下所示,使用官方 Wordpress API 在内存和数据库中重新分配这些权限
function add_capabilities() {
$author = get_role('author');
$caps = array(
'edit_others_posts',
'edit_others_pages',
'publish_posts',
'delete_posts',
'delete_published_posts',
);
foreach ($caps as $cap) {
$author->add_cap($cap);
}
}
add_action('init', 'add_capabilities');
然后,您可以从您的 users 管理页面确保为用户分配了所需的作者角色。
方法 2 - 手动访问和更新您的数据库
假设wp_ 作为您的数据库前缀,您可以确保确实为用户分配了author 的角色,如果没有手动分配它。这是在您的wp_usermeta 表中,您应该会看到一条记录,其中包含有问题的user_id 和名称wp_capabilities。该值存储一个 php 序列化的角色数组,例如,如果用户只是一个作者,则该值将是 a:1:{s:6:"author";b:1;}。
现在您已确保用户确实在角色中,所有角色功能都存储在 option_name wp_user_roles 内的 wp_options 表中。同样,这是一个长序列化的 php 关联数组,其结构如下(假设 $roleName 是任何角色,例如“作者”)
["$roleName"=>[
'name'=>"$roleName",
'capabilities'=>[
'edit_others_posts',
'edit_others_pages',
'publish_posts',
'delete_posts',
'delete_published_posts',
]
]
]
如果您有备份或其他工作位置,则可以恢复它。如果您希望手动修改这些值,由于需要 php 序列化,我建议在 php 中编写自定义代码来实现,例如,如果使用 Solution 1 没有帮助或 Wordpress 方法不可用,例如。从不同的客户端/服务器/位置工作。
其他资源和参考资料
参见官方 Wordpress 文档的实现
$author = get_role('作者'); --> 在$author 中返回一个WP_Role
下面包含了一个调用 remove_cap 和我将引用从 https://developer.wordpress.org/reference/classes/wp_roles/ 检索的 add_cap 的实现:
/**
* Add capability to role.
*
* @since 2.0.0
*
* @param string $role Role name.
* @param string $cap Capability name.
* @param bool $grant Optional. Whether role is capable of performing capability.
* Default true.
*/
public function add_cap( $role, $cap, $grant = true ) {
if ( ! isset( $this->roles[ $role ] ) ) {
return;
}
$this->roles[ $role ]['capabilities'][ $cap ] = $grant;
if ( $this->use_db ) {
update_option( $this->role_key, $this->roles );
}
}
/**
* Remove capability from role.
*
* @since 2.0.0
*
* @param string $role Role name.
* @param string $cap Capability name.
*/
public function remove_cap( $role, $cap ) {
if ( ! isset( $this->roles[ $role ] ) ) {
return;
}
unset( $this->roles[ $role ]['capabilities'][ $cap ] );
if ( $this->use_db ) {
update_option( $this->role_key, $this->roles );
}
}