zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Otter详解
    为什么要使用Netty
    haproxy实现mysql集群负载均衡
    Mysql主从复制
    java编程思想读书笔记三(HashMap详解)
    代码界的石器时代
    补码的产生与应用
    java编程思想读书笔记二(对象的创建)
    java编程思想读书笔记一(面向对象)
    Apache VFS
  • 原文地址:https://www.cnblogs.com/ryanzheng/p/10562448.html
Copyright © 2011-2022 走看看