在 WordPress v5.5.1 中,我使用了以下功能来限制作者发布帖子:
function set_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->remove_cap($cap);
}
}
add_action('init', 'set_capabilities');
Run Code Online (Sandbox Code Playgroud)
这导致完全删除帖子页面并在wp-admin/post-new.php
.
我已删除该set_capabilities()
功能,但仍然收到错误消息“抱歉,您无权访问此页面。”。
我试过重置wp-capabilities
,它仍然对我不起作用。
我尝试添加一个具有author
角色的新用户,新用户也有同样的问题。
我怎样才能让作者创建一个wp-admin/post-new.php
再次访问的帖子?
调用$author->remove_cap($cap)
该功能后,该功能不仅在内存中而且在数据库中都从作者角色中删除(有关实现和链接,请参阅下面的参考部分)。因此,删除对角色的调用set_capabilities()
或向角色添加新用户不会重置角色功能。
您可以执行相反的操作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');
Run Code Online (Sandbox Code Playgroud)
然后,您可以从users
管理页面确保为用户分配所需的作者角色。
假设wp_
您的数据库前缀,您可以确保用户确实被分配了角色author
,如果没有手动分配的话。这是在您的表中,您应该看到一条带有相关问题和名称的wp_usermeta
记录。该值存储角色的 php 序列化数组,例如,如果用户只是作者,则该值将为。user_id
wp_capabilities
a:1:{s:6:"author";b:1;}
现在您已确保用户确实处于该角色中,所有角色功能都存储在wp_options
option_name 内的表中wp_user_roles
。同样,这是一个长序列化的 php 关联数组,其结构如下(假设$roleName
是任何角色,例如“作者”)
["$roleName"=>[
'name'=>"$roleName",
'capabilities'=>[
'edit_others_posts',
'edit_others_pages',
'publish_posts',
'delete_posts',
'delete_published_posts',
]
]
]
Run Code Online (Sandbox Code Playgroud)
如果您有备份或其他工作位置,则可以将其恢复。如果您希望手动修改这些值,由于需要 php 序列化,我建议在 php 中编写自定义代码来实现,例如如果使用Solution 1
没有帮助或 WordPress 方法不可用,例如最后的手段。从不同的客户端/服务器/位置工作。
请参阅 WordPress 官方文档的实现
$author = get_role ('作者'); --> 返回一个WP_Role$author
下面包含了从https://developer.wordpress.org/reference/classes/wp_roles/remove_cap
检索到的被调用和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 );
}
}
Run Code Online (Sandbox Code Playgroud)