网站源码二次开发教程:WordPress插件实现自定义用户角色权限管理实战

网站源码二次开发教程:<a href="https://www.ezdj.cn/tag/105"><b>WordPress</b></a>插件实现自定义用户角色权限管理实战

插件开发环境搭建

在开始wordpress插件二次开发前,需确保开发环境满足以下要求:

配置项 要求
PHP版本 PHP 7.4或更高版本
WordPress版本 WordPress 5.8以上
开发工具 VS Code或类似代码编辑器
数据库 MySQL 5.7或更高版本

以下是创建WordPress插件基础框架的代码:

/
  自定义用户角色权限管理插件
 /
/
Plugin Name: Custom User Role Manager
Description: WordPress自定义用户角色与权限管理系统
Version: 1.0.0
Author: 技术专家
Author URI: https://example.com
License: GPL2
/

if (!defined('ABSPATH')) {
    exit;
}

require_once(plugin_dir_path(__FILE__) . 'includes/custom-role-manager.php');

此代码创建了一个基础插件框架,其中包含核心逻辑的引入路径。

自定义用户角色注册

使用WordPress add_role 函数创建自定义角色,以下是示例代码:

/
  注册高级编辑者角色
 /
function custom_role_manager_register_roles() {
    add_role(
        'advanced_editor', // 角色ID
        '高级编辑者', // 显示名称
        array(
            'read' => true,
            'edit_posts' => true,
            'edit_others_posts' => true,
            'publish_posts' => true,
            'delete_posts' => true,
            'edit_pages' => true,
            'delete_pages' => true,
            'manage_options' => false
        )
    );
}
add_action('init', 'custom_role_manager_register_roles');

代码中定义了advanced_editor角色,并赋予其编辑文章和页面权限,但无管理选项权限。

权限管理功能实现

创建管理页面

使用add_menu_page函数创建管理页面:

/
  添加权限管理设置页面
 /
function custom_role_manager_add_admin_menu() {
    add_menu_page(
        '角色权限管理', // 页面标题
        '角色管理', // 菜单标题
        'manage_options', // 权限要求
        'custom-role-manager',
        'custom_role_manager_admin_page',
        'dashicons-users',
        6 // 位置
    );
}
add_action('admin_menu', 'custom_role_manager_add_admin_menu');

实现页面显示逻辑

创建页面内容显示函数:

/
  角色权限管理页面内容
 /
function custom_role_manager_admin_page() {
    ?>
    

角色权限管理

<?php $roles = get_roles(); foreach ($roles as $role) { echo ""; echo ""; echo ""; echo ""; } ?>
角色名称 权限设置
{$role->name}"; // 显示权限复选框 foreach (get_permissions() as $perm) { echo "
"; } echo "
<?php }

保存权限设置

添加保存逻辑处理函数:

/
  保存角色权限设置
 /
function custom_role_manager_save_settings() {
    if (isset($_POST['role_permissions'])) {
        foreach ($_POST['role_permissions'] as $role_id => $permissions) {
            $role = get_role($role_id);
            if ($role) {
                foreach ($permissions as $perm => $value) {
                    if ($value) {
                        $role->add_cap($perm);
                    } else {
                        $role->remove_cap($perm);
                    }
                }
            }
        }
        wp_redirect(add_query_arg('settings-updated', 'true', admin_url('admin.php?page=custom-role-manager')));
        exit;
    }
}
add_action('admin_post_custom_role_manager_save', 'custom_role_manager_save_settings');

/
  检查设置更新通知
 /
function custom_role_manager_settings_updated() {
    if (isset($_GET['settings-updated'])) {
        ?>
        

角色权限设置已成功保存!

<?php } } add_action('admin_notices', 'custom_role_manager_settings_updated');

API集成与扩展

REST API集成示例

使用REST API获取当前用户角色权限:

/
  获取当前用户角色权限数据
 /
async function fetchUserRolePermissions() {
    try {
        const response = await fetch('/wp-json/custom-role-manager/permissions');
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('获取权限数据失败:', error);
    }
}

创建REST路由处理函数:

/
  注册REST API路由
 /
function custom_role_manager_register_rest_routes() {
    register_rest_route(
        'custom-role-manager/v1',
        '/permissions',
        array(
            'methods' => 'GET',
            'callback' => 'custom_role_manager_get_permissions',
        )
    );
}
add_action('rest_api_init', 'custom_role_manager_register_rest_routes');

/
  REST API权限获取处理
 /
function custom_role_manager_get_permissions($request) {
    $permissions = array();
    $user = wp_get_current_user();
    $roles = $user->roles;
    
    foreach ($roles as $role) {
        $permissions[$role] = array();
        $caps = get_role($role)->capabilities;
        
        foreach ($caps as $cap => $value) {
            $permissions[$role][$cap] = current_user_can($cap);
        }
    }
    
    return new WP_REST_Response($permissions, 200);
}

与其他系统集成

以下代码示例展示了如何与CRM系统集成:

/
  通过Webhook同步用户角色
 /
function custom_role_manager_crm_integration() {
    // 检查是否为Webhook请求
    if (isset($_GET['action']) && $_GET['action'] === 'sync_roles') {
        check_ajax_referer('crm_webhook');
        
        // 获取CRM发送的数据
        $crm_data = json_decode(file_get_contents('php://input'), true);
        
        // 更新WordPress用户角色
        foreach ($crm_data['users'] as $user_data) {
            $user = get_user_by('email', $user_data['email']);
            if ($user) {
                $new_role = $user_data['role'];
                $current_role = $user->roles[0];
                
                if ($new_role !== $current_role) {
                    $user->set_role($new_role);
                }
            }
        }
        
        wp_send_json_success();
    }
}
add_action('wp_ajax_custom_role_manager_crm_sync', 'custom_role_manager_crm_integration');
add_action('wp_ajax_nopriv_custom_role_manager_crm_sync', 'custom_role_manager_crm_integration');

安全加固措施

权限验证

确保所有敏感操作都进行权限验证:

/
  验证用户是否具有管理员权限
 /
function custom_role_manager_verify_admin() {
    if (!current_user_can('manage_options')) {
        wp_die('您没有足够的权限访问此页面!');
    }
}
add_action('admin_init', 'custom_role_manager_verify_admin');

输入验证

对所有用户输入进行验证和清理:

/
  安全地处理用户输入
 /
function custom_role_manager_sanitize_input($input) {
    if (is_array($input)) {
        return array_map('sanitize_text_field', $input);
    } else {
        return sanitize_text_field($input);
    }
}

操作日志

记录重要操作以便审计:

/
  记录操作日志
 /
function custom_role_manager_log_action($action, $user_id, $data) {
    $log_entry = array(
        'time' => current_time('timestamp'),
        'user_id' => $user_id,
        'action' => $action,
        'details' => $data
    );
    
    // 保存到数据库或第三方日志系统
    // 示例:保存到自定义表中
    global $wpdb;
    $table_name = $wpdb->prefix . 'role_manager_logs';
    $wpdb->insert($table_name, $log_entry);
}

以上文章内容为AI生成,仅供参考,需辨别文章内容信息真实有效

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。