Wordpress 为用户或角色 role 添加 capabilities(权限)

首先查看角色具有哪些权限:

$admin_role_set = get_role( 'administrator' )->capabilities;
$author_role_set = get_role( 'author' )->capabilities;

 

注意:修改权限的行为是永久性的,除非你手动删除该权限,因为角色的权限设置是保存到数据库中的(保存在数据表 wp_options,字段名称option_name,值为 wp_user_roles),

SQL 命令:

SELECT * FROM `wp_options` WHERE option_name = 'wp_user_roles';

 

 

 

 

 

可以通过两种方式添加权限:

<?php 
  global $wp_roles; // global class wp-includes/capabilities.php
  $wp_roles->add_cap( $role, $cap ); 
?> 
or 
<?php
  $role = get_role( 'author' );
  $role->add_cap( $cap );
?> 

Parameters 参数介绍:

$cap 代表权限名称,为字符串,如 'unfiltered_html'

 

 

Example:

function add_theme_caps() {
    // gets the author role
    $role = get_role( 'author' );

    // This only works, because it accesses the class instance.
    // would allow the author to edit others' posts for current theme only
    $role->add_cap( 'edit_others_posts' ); 
}
add_action( 'admin_init', 'add_theme_caps');

 

为特定用户添加功能权限:

$user = new WP_User( $user_id );
$user->add_cap( 'can_edit_posts' );

 

add_cap  的定义位于下列文件中:

wp-includes/class-wp-role.php

wp-includes/class-wp-roles.php

wp-includes/class-wp-user.php


  unfiltered_html 权限允许用户在文章或评论等地方插入 js 代码等特殊标签,但是只有管理员以及 Editor 默认有该权限,具体权限表请查阅:

https://codex.wordpress.org/Roles_and_Capabilities#Author

如果需要为 Author 添加该权限,需要在 functions.php 中增加如下代码:

$author_role_add_cap = get_role('author');
$author_role_add_cap->add_cap('unfiltered_html');
// Add unfiltered html for editor authority
function km_add_unfiltered_html_capability_to_editors( $caps, $cap, $user_id ) {
  if ( 'unfiltered_html' === $cap && ( user_can( $user_id, 'editor' ) || user_can( $user_id, 'author' ) ) ) {
    $caps = array( 'unfiltered_html' );
  }
  return $caps;
}
add_filter( 'map_meta_cap', 'km_add_unfiltered_html_capability_to_editors', 1, 3 );

 

增加以上代码后,就可以在文章编辑中插入 js 代码。

 

资料来源:

https://wordpress.stackexchange.com/questions/227411/how-to-get-all-capabilities-of-an-existing-user-role

https://codex.wordpress.org/Function_Reference/add_cap

转载于:https://www.cnblogs.com/ryanzheng/p/10562448.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值