WordPress函数:current_user_can:用户权限检测

编辑文章

简介

current_user_can() 是WordPress的核心权限检查函数,用于判断当前登录用户是否具备执行某项操作的能力(Capability)。它广泛应用于插件和主题开发中,用于在前端或后台界面中控制功能的可见性与可访问性,是构建安全可靠的WordPress应用的重要基础。

语法

此函数定义于 wp-includes/capabilities.php 文件中。它内部调用 WP_User 类的 has_cap() 方法进行实际的能力检查,并支持可变参数以实现对象级别的细粒度权限控制。

current_user_can( string $capability, mixed ...$args ): bool

核心文件位置wp-includes/capabilities.php
内部调用链current_user_can()wp_get_current_user()WP_User->has_cap()

参数详细说明

参数 类型 是否必需 具体取值说明 典型示例
$capability 字符串 能力名称字符串,不是角色名称。

WordPress核心定义了数百种标准能力,分为几类:
1. 通用管理能力:如 'manage_options'(管理设置)、'manage_categories'(管理分类)
2. 文章类型相关能力:如 'edit_posts'(编辑文章)、'publish_pages'(发布页面)
3. 用户相关能力:如 'edit_users'(编辑用户)、'delete_users'(删除用户)
4. 媒体相关能力:如 'upload_files'(上传文件)
5. 元能力(Meta Capabilities):如 'edit_post''delete_user',通常需要额外参数

如何查找现有能力
– 查看WordPress官方文档的”Roles and Capabilities”页面
– 安装”User Role Editor”等插件查看所有能力
– 在代码中搜索 'capability' 参数查看注册时定义的能力

'edit_posts'
'manage_options'
'edit_post'
'upload_files'
...$args 混合类型 可变参数,根据检查的能力类型传递不同值:

1. 对象ID(整数):用于对象级别的细粒度检查
edit_post:第二个参数是文章ID,如 123
edit_user:第二个参数是用户ID,如 456
edit_term:第二个参数是分类术语ID,如 789

2. 多个参数:某些能力需要多个参数
assign_term:需要分类术语ID和分类法名称,如 array(123, 'category')

3. 无参数:通用能力检查不需要额外参数
edit_postsmanage_options

重要:不是所有能力都接受额外参数。传递不需要的参数会被忽略,但不会报错。

current_user_can('edit_post', 123)
current_user_can('edit_user', 456)
current_user_can('assign_term', array(123, 'category'))

返回值说明

  • 返回类型:布尔值(bool)
  • 返回 true:当前用户拥有指定的能力
  • 返回 false:当前用户没有指定能力,或用户未登录
  • 特殊说明:当检查一个不存在的或拼写错误的能力时,通常会返回 false,不会产生错误

用法

基础用法

1. 检查通用管理权限

// 检查是否是管理员(拥有管理设置的能力)
if ( current_user_can( 'manage_options' ) ) {
    echo '您是网站管理员,可以访问设置页面。';

    // 安全提示:即使是管理员可见的内容,如果包含用户输入也需要转义
    $admin_message = get_option( 'admin_notice' );
    echo '<div class="notice">' . esc_html( $admin_message ) . '</div>';
}

// 检查用户是否能发布文章
if ( current_user_can( 'publish_posts' ) ) {
    // 显示发布文章的表单或链接
    $publish_url = admin_url( 'post-new.php' );
    echo '<a href="' . esc_url( $publish_url ) . '" class="button">发布新文章</a>';
}

2. 控制菜单和功能的显示

// 在主题模板文件中(如 header.php)
// 仅对编辑者及以上权限的用户显示编辑链接
if ( current_user_can( 'edit_others_posts' ) ) {
    $current_post_id = get_the_ID();
    if ( $current_post_id ) {
        $edit_link = get_edit_post_link( $current_post_id );
        echo '<a href="' . esc_url( $edit_link ) . '" class="post-edit-link">编辑本文</a>';
    }
}

// 在插件设置页面中限制访问
function my_plugin_admin_page() {
    // 必须放在函数顶部,确保在输出任何内容前检查权限
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( 
            __( '您没有权限访问此页面。', 'my-plugin' ),
            __( '权限不足', 'my-plugin' ),
            array( 'response' => 403 )
        );
    }

    // 只有管理员才能看到下面的内容
    echo '<div class="wrap">';
    echo '<h1>' . esc_html__( '插件设置', 'my-plugin' ) . '</h1>';
    // ... 更多设置代码
}

进阶用法

1. 对象级别的细粒度权限检查

// 假设我们在单篇文章页面(single.php)中
$post_id = get_the_ID();

// 检查当前用户是否可以编辑这篇文章
// 注意:这里使用的是 'edit_post'(单数),不是 'edit_posts'(复数)
if ( current_user_can( 'edit_post', $post_id ) ) {
    // 用户可以编辑这篇文章,显示编辑链接
    $edit_url = get_edit_post_link( $post_id );
    echo '<a href="' . esc_url( $edit_url ) . '" class="edit-post">编辑</a>';

    // 同时检查删除权限
    if ( current_user_can( 'delete_post', $post_id ) ) {
        $delete_url = get_delete_post_link( $post_id, '', true );
        echo '<a href="' . esc_url( $delete_url ) . '" class="delete-post" onclick="return confirm(\'确定要删除吗?\')">删除</a>';
    }
}

// 在用户管理相关功能中
function maybe_show_user_edit_link( $user_id ) {
    // 检查当前用户是否有权限编辑这个特定用户
    if ( current_user_can( 'edit_user', $user_id ) ) {
        $edit_link = get_edit_user_link( $user_id );
        return '<a href="' . esc_url( $edit_link ) . '">编辑用户</a>';
    }

    return '';
}

2. 自定义文章类型的权限检查

// 假设我们注册了一个自定义文章类型 'product'
add_action( 'init', 'register_product_post_type' );
function register_product_post_type() {
    register_post_type( 'product', array(
        'public' => true,
        'capability_type' => 'product', // 关键设置
        'map_meta_cap' => true,         // 启用元能力映射
        'capabilities' => array(
            'edit_post' => 'edit_product',
            'read_post' => 'read_product',
            'delete_post' => 'delete_product',
            'edit_posts' => 'edit_products',
            'edit_others_posts' => 'edit_others_products',
            'publish_posts' => 'publish_products',
            'read_private_posts' => 'read_private_products',
            'delete_posts' => 'delete_products',
        ),
        // ... 其他参数
    ) );
}

// 使用自定义能力进行检查
$product_id = 123; // 假设的产品ID

// 检查当前用户是否可以编辑这个特定产品
if ( current_user_can( 'edit_product', $product_id ) ) {
    // 用户有编辑此产品的权限
    echo '可以编辑产品 #' . intval( $product_id );
}

// 检查用户是否有编辑任何产品的能力
if ( current_user_can( 'edit_products' ) ) {
    echo '您可以管理产品。';
}

3. 结合REST API的权限检查

// 在REST API端点注册中定义权限回调
register_rest_route( 'myplugin/v1', '/protected-data/', array(
    'methods' => 'GET',
    'callback' => 'get_protected_data',
    'permission_callback' => function() {
        // 权限回调必须返回 true 或 false
        // 检查用户是否有访问此端点所需的能力
        return current_user_can( 'read_private_posts' );
    },
) );

function get_protected_data( $request ) {
    // 只有在权限回调返回true时,才会执行到这里
    $data = array( 'message' => '这是受保护的数据' );
    return rest_ensure_response( $data );
}

易错点

1. 混淆”角色”与”能力”

错误示例

// 错误:检查用户是否属于某个角色
if ( current_user_can( 'editor' ) ) { // 'editor' 是角色,不是能力
    // 这个方法可能在某些情况下工作,但不可靠
}

错误原因:WordPress的权限系统基于能力(Capabilities),而非角色(Roles)。角色只是能力的集合。直接检查角色名称不是标准做法,且在不同站点配置下可能失效。

正确做法

// 正确:检查用户是否具备特定角色通常拥有的核心能力
if ( current_user_can( 'edit_others_posts' ) ) {
    // 这通常意味着用户是编辑者或更高级别的角色
    // 更精确地反映了权限需求
}

// 如果需要检查特定角色,使用专门函数
$user = wp_get_current_user();
if ( in_array( 'editor', (array) $user->roles ) ) {
    // 这是检查角色的正确方法
}

2. 错误使用可变参数

错误示例

// 错误:为不需要参数的能力传递参数
if ( current_user_can( 'edit_posts', $post_id ) ) {
    // $post_id 参数被忽略,实际检查的是全局的 edit_posts 能力
}

// 错误:为对象能力不传递必要的参数
if ( current_user_can( 'edit_post' ) ) { // 缺少文章ID参数
    // 这实际上会检查用户是否有 'edit_posts' 能力
    // 而不是对特定文章的权限
}

正确做法

// 明确区分全局能力和对象能力
// 全局能力检查(不需要额外参数)
if ( current_user_can( 'edit_posts' ) ) {
    // 用户可以在网站中编辑文章
}

// 对象能力检查(需要额外参数)
if ( current_user_can( 'edit_post', $post_id ) ) {
    // 用户可以编辑这篇特定文章
}

3. 权限检查时机不当

错误示例

// 在用户信息加载完成前检查权限
add_action( 'after_setup_theme', 'my_early_check' );
function my_early_check() {
    if ( current_user_can( 'manage_options' ) ) {
        // 在 after_setup_theme 阶段,当前用户可能尚未完全加载
        // 特别是使用对象缓存时可能出现问题
    }
}

解决方案

// 在适当的钩子中检查权限
add_action( 'init', 'my_safe_check' ); // init 钩子通常是安全的
function my_safe_check() {
    if ( current_user_can( 'manage_options' ) ) {
        // 此时用户信息已加载完成
    }
}

// 对于特定上下文,使用更晚的钩子
add_action( 'wp', 'my_frontend_check' ); // 前端检查
add_action( 'admin_init', 'my_admin_check' ); // 后台检查

4. 安全性疏忽

错误示例

// 直接使用未经验证的用户输入进行权限检查
$post_id = $_GET['post_id']; // 来自URL参数,可能被篡改
if ( current_user_can( 'edit_post', $post_id ) ) {
    // 如果攻击者传递了其他文章ID,可能绕过权限检查
    delete_post( $post_id ); // 危险操作!
}

安全做法

// 始终验证和清理用户输入
$post_id = isset( $_GET['post_id'] ) ? intval( $_GET['post_id'] ) : 0;

// 先验证对象是否存在
if ( $post_id && get_post( $post_id ) ) {
    // 然后进行权限检查
    if ( current_user_can( 'delete_post', $post_id ) ) {
        // 执行安全操作
        wp_delete_post( $post_id, true );
    } else {
        wp_die( '您没有权限删除此文章。' );
    }
} else {
    wp_die( '文章不存在。' );
}

5. 性能问题

错误示例

// 在循环中进行重复的权限检查
$all_posts = get_posts( array( 'numberposts' => -1 ) );
foreach ( $all_posts as $post ) {
    // 每次循环都调用 current_user_can,效率低下
    if ( current_user_can( 'edit_post', $post->ID ) ) {
        // 处理文章...
    }
}

优化方案

// 在查询时预过滤
$current_user_id = get_current_user_id();
$editable_posts = get_posts( array(
    'author' => $current_user_id, // 首先获取用户自己的文章
    'post_status' => array( 'publish', 'pending', 'draft', 'private' ),
    'posts_per_page' => 50, // 限制数量,避免获取过多
) );

// 如果还需要检查用户是否有编辑他人文章的权限
if ( current_user_can( 'edit_others_posts' ) ) {
    // 获取更多文章
    $others_posts = get_posts( array(
        'author__not_in' => array( $current_user_id ),
        'post_status' => array( 'publish', 'pending' ),
        'posts_per_page' => 50,
    ) );
    $editable_posts = array_merge( $editable_posts, $others_posts );
}

最佳实践

性能优化策略

1. 缓存权限检查结果

对于频繁检查且不经常变化的权限,可以考虑缓存结果。

function can_user_manage_products( $user_id = null ) {
    if ( null === $user_id ) {
        $user_id = get_current_user_id();
    }

    $cache_key = "user_can_manage_products_{$user_id}";
    $cached_result = wp_cache_get( $cache_key, 'user_capabilities' );

    if ( false !== $cached_result ) {
        return (bool) $cached_result;
    }

    // 模拟一个复杂的权限检查逻辑
    $user = get_user_by( 'id', $user_id );
    $can_manage = false;

    if ( $user ) {
        // 检查多个能力
        $can_manage = $user->has_cap( 'edit_products' ) 
                   || $user->has_cap( 'manage_product_terms' )
                   || $user->has_cap( 'manage_woocommerce' ); // 如果是WooCommerce

        // 缓存结果,有效期1小时
        wp_cache_set( $cache_key, (int) $can_manage, 'user_capabilities', HOUR_IN_SECONDS );
    }

    return $can_manage;
}

// 使用缓存的函数
if ( can_user_manage_products() ) {
    // 用户有管理产品的权限
}

2. 批量检查权限

当需要对多个对象进行权限检查时,批量处理可以提高效率。

function check_multiple_post_permissions( $post_ids, $capability = 'edit_post' ) {
    if ( empty( $post_ids ) ) {
        return array();
    }

    $current_user_id = get_current_user_id();
    $results = array();

    // 获取所有文章的详细信息
    $posts = get_posts( array(
        'post__in' => array_map( 'intval', $post_ids ),
        'posts_per_page' => -1,
        'post_type' => 'any',
        'fields' => 'ids',
    ) );

    // 批量检查权限(简化示例,实际可能需要更复杂逻辑)
    foreach ( $posts as $post_id ) {
        $results[ $post_id ] = current_user_can( $capability, $post_id );
    }

    return $results;
}

// 使用批量检查
$post_ids_to_check = array( 1, 2, 3, 4, 5 );
$permissions = check_multiple_post_permissions( $post_ids_to_check, 'edit_post' );

foreach ( $permissions as $post_id => $can_edit ) {
    if ( $can_edit ) {
        echo "可以编辑文章 #" . intval( $post_id ) . "<br>";
    }
}

代码可维护性设计

1. 创建权限检查辅助类

将复杂的权限逻辑封装到专门的类中,提高代码复用性。

class MyPlugin_Permission_Checker {

    /**
     * 检查用户是否可访问高级功能
     *
     * @param int|null $user_id 用户ID,null表示当前用户
     * @return bool
     */
    public static function can_access_premium_features( $user_id = null ) {
        if ( null === $user_id ) {
            $user_id = get_current_user_id();
        }

        // 规则1:管理员或编辑者可以直接访问
        if ( user_can( $user_id, 'edit_others_posts' ) ) {
            return true;
        }

        // 规则2:订阅了高级计划的用户可以访问
        $user_plan = get_user_meta( $user_id, 'subscription_plan', true );
        if ( 'premium' === $user_plan || 'enterprise' === $user_plan ) {
            return true;
        }

        // 规则3:特定用户组的成员可以访问
        if ( self::is_user_in_group( $user_id, 'beta_testers' ) ) {
            return true;
        }

        return false;
    }

    /**
     * 检查用户是否可以管理特定类型的内容
     *
     * @param string $content_type 内容类型
     * @param int|null $user_id 用户ID
     * @return bool
     */
    public static function can_manage_content_type( $content_type, $user_id = null ) {
        $capability_map = array(
            'post' => 'edit_posts',
            'page' => 'edit_pages',
            'product' => 'edit_products',
            'course' => 'edit_courses',
        );

        if ( ! isset( $capability_map[ $content_type ] ) ) {
            return false;
        }

        return user_can( $user_id ?: get_current_user_id(), $capability_map[ $content_type ] );
    }

    /**
     * 检查用户是否在特定用户组中(示例方法)
     */
    private static function is_user_in_group( $user_id, $group_name ) {
        // 实现用户组检查逻辑
        $user_groups = get_user_meta( $user_id, 'user_groups', true );
        return is_array( $user_groups ) && in_array( $group_name, $user_groups, true );
    }
}

// 使用权限检查类
if ( MyPlugin_Permission_Checker::can_access_premium_features() ) {
    echo '您可以访问高级功能。';
}

if ( MyPlugin_Permission_Checker::can_manage_content_type( 'product' ) ) {
    echo '您可以管理产品。';
}

2. 使用常量定义能力名称

避免在代码中硬编码能力名称,使用常量提高可维护性。

// 在插件主文件中定义能力常量
define( 'MYPLUGIN_CAP_MANAGE_SETTINGS', 'myplugin_manage_settings' );
define( 'MYPLUGIN_CAP_VIEW_REPORTS', 'myplugin_view_reports' );
define( 'MYPLUGIN_CAP_EDIT_PRODUCTS', 'myplugin_edit_products' );

// 在插件激活时分配能力
register_activation_hook( __FILE__, 'myplugin_activate' );
function myplugin_activate() {
    $roles_with_settings = array( 'administrator', 'shop_manager' );

    foreach ( $roles_with_settings as $role_name ) {
        $role = get_role( $role_name );
        if ( $role ) {
            $role->add_cap( MYPLUGIN_CAP_MANAGE_SETTINGS );
            $role->add_cap( MYPLUGIN_CAP_VIEW_REPORTS );
        }
    }

    // 只为编辑者及以上角色添加产品编辑能力
    $roles_with_products = array( 'administrator', 'editor', 'shop_manager' );
    foreach ( $roles_with_products as $role_name ) {
        $role = get_role( $role_name );
        if ( $role ) {
            $role->add_cap( MYPLUGIN_CAP_EDIT_PRODUCTS );
        }
    }
}

// 在代码中使用常量进行检查
if ( current_user_can( MYPLUGIN_CAP_MANAGE_SETTINGS ) ) {
    // 显示设置页面
}

if ( current_user_can( MYPLUGIN_CAP_EDIT_PRODUCTS ) ) {
    // 显示产品管理界面
}

安全性增强措施

1. 结合nonce验证防止CSRF攻击

即使有权限检查,也需要防止跨站请求伪造。

// 在表单或链接中添加nonce
function render_admin_action_button() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $action_url = admin_url( 'admin-post.php' );
    $nonce = wp_create_nonce( 'myplugin_admin_action' );
    ?>
    <form method="post" action="<?php echo esc_url( $action_url ); ?>">
        <input type="hidden" name="action" value="myplugin_admin_action">
        <input type="hidden" name="myplugin_nonce" value="<?php echo esc_attr( $nonce ); ?>">
        <input type="hidden" name="item_id" value="<?php echo esc_attr( get_the_ID() ); ?>">
        <?php submit_button( '执行管理员操作' ); ?>
    </form>
    <?php
}

// 处理表单提交时验证nonce和权限
add_action( 'admin_post_myplugin_admin_action', 'handle_myplugin_admin_action' );
function handle_myplugin_admin_action() {
    // 1. 检查nonce
    if ( ! isset( $_POST['myplugin_nonce'] ) || 
         ! wp_verify_nonce( $_POST['myplugin_nonce'], 'myplugin_admin_action' ) ) {
        wp_die( '安全验证失败。' );
    }

    // 2. 检查权限
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( '您没有权限执行此操作。' );
    }

    // 3. 验证和处理数据
    $item_id = isset( $_POST['item_id'] ) ? intval( $_POST['item_id'] ) : 0;

    // 4. 执行安全的管理员操作
    // ...

    // 5. 重定向回原页面
    wp_redirect( wp_get_referer() ?: admin_url() );
    exit;
}

2. 实现多层安全防御

class Secure_Content_Manager {

    /**
     * 安全地删除内容
     */
    public static function delete_content( $content_id, $content_type = 'post' ) {
        // 第一层:验证用户是否登录
        if ( ! is_user_logged_in() ) {
            return new WP_Error( 'not_logged_in', '用户未登录。' );
        }

        // 第二层:基础权限检查
        if ( 'post' === $content_type && ! current_user_can( 'delete_posts' ) ) {
            return new WP_Error( 'insufficient_permissions', '没有删除权限。' );
        }

        // 第三层:对象级权限检查
        if ( 'post' === $content_type && ! current_user_can( 'delete_post', $content_id ) ) {
            return new WP_Error( 'object_permission_denied', '没有删除此内容的权限。' );
        }

        // 第四层:业务逻辑验证
        $content = get_post( $content_id );
        if ( ! $content ) {
            return new WP_Error( 'not_found', '内容不存在。' );
        }

        // 第五层:防止误删重要内容
        if ( self::is_protected_content( $content_id ) ) {
            return new WP_Error( 'protected_content', '此内容受保护,不能删除。' );
        }

        // 所有检查通过,执行删除
        $result = wp_delete_post( $content_id, true );

        if ( $result ) {
            // 记录审计日志
            self::log_audit_trail( get_current_user_id(), 'delete', $content_type, $content_id );
            return true;
        }

        return new WP_Error( 'delete_failed', '删除失败。' );
    }

    /**
     * 检查是否是受保护的内容
     */
    private static function is_protected_content( $content_id ) {
        // 实现保护逻辑,如检查特定元数据
        return (bool) get_post_meta( $content_id, '_protected', true );
    }

    /**
     * 记录审计日志
     */
    private static function log_audit_trail( $user_id, $action, $content_type, $content_id ) {
        $log_entry = array(
            'user_id' => $user_id,
            'action' => $action,
            'content_type' => $content_type,
            'content_id' => $content_id,
            'timestamp' => current_time( 'mysql' ),
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '',
        );

        // 存储到自定义数据库表或文件中
        // ...
    }
}

// 安全地使用多层防御
$result = Secure_Content_Manager::delete_content( 123 );
if ( is_wp_error( $result ) ) {
    echo '错误:' . esc_html( $result->get_error_message() );
} else {
    echo '内容已安全删除。';
}

与现代WordPress开发结合

1. 在区块编辑器中集成权限检查

// 注册一个只有特定用户能看到的区块
add_action( 'init', 'register_restricted_block' );
function register_restricted_block() {
    register_block_type( 'myplugin/restricted-content', array(
        'title' => '受限制的内容',
        'description' => '只有特定权限的用户可以看到此区块。',
        'category' => 'common',
        'icon' => 'lock',
        'supports' => array(
            'html' => false,
        ),
        'attributes' => array(
            'requiredCapability' => array(
                'type' => 'string',
                'default' => 'edit_posts',
            ),
        ),
        // 在前端渲染时检查权限
        'render_callback' => 'render_restricted_block',
        // 在编辑器中控制可见性
        'uses_context' => array( 'postId', 'postType' ),
    ) );
}

function render_restricted_block( $attributes, $content, $block ) {
    // 获取需要的权限
    $required_cap = $attributes['requiredCapability'] ?? 'edit_posts';

    // 检查是否针对特定文章
    $post_id = $block->context['postId'] ?? null;

    if ( $post_id ) {
        // 检查对特定文章的权限
        $has_access = current_user_can( $required_cap, $post_id );
    } else {
        // 检查全局权限
        $has_access = current_user_can( $required_cap );
    }

    if ( ! $has_access ) {
        // 用户没有权限,返回空或替代内容
        if ( is_user_logged_in() ) {
            return '<div class="restricted-notice">' . esc_html__( '您没有权限查看此内容。', 'myplugin' ) . '</div>';
        } else {
            return '<div class="restricted-notice">' . esc_html__( '请登录后查看此内容。', 'myplugin' ) . '</div>';
        }
    }

    // 用户有权限,渲染区块内容
    return '<div class="restricted-content">' . $content . '</div>';
}

2. 在REST API中使用细粒度权限控制

// 注册需要复杂权限检查的REST API端点
add_action( 'rest_api_init', 'register_secure_rest_endpoints' );
function register_secure_rest_endpoints() {
    // 端点1:获取用户自己的草稿文章
    register_rest_route( 'myplugin/v1', '/my-drafts', array(
        'methods' => 'GET',
        'callback' => 'get_my_drafts',
        'permission_callback' => function( $request ) {
            // 必须是已登录用户
            if ( ! is_user_logged_in() ) {
                return false;
            }

            // 必须有编辑文章的权限
            return current_user_can( 'edit_posts' );
        },
    ) );

    // 端点2:更新特定文章(需要对象级权限)
    register_rest_route( 'myplugin/v1', '/posts/(?P<id>\d+)', array(
        'methods' => 'POST',
        'callback' => 'update_post',
        'permission_callback' => function( $request ) {
            // 检查权限,包括文章ID参数
            $post_id = $request->get_param( 'id' );

            // 注意:REST API权限回调中,用户可能不是"当前用户"
            // 需要使用 user_can() 而不是 current_user_can()
            $user_id = get_current_user_id();

            return user_can( $user_id, 'edit_post', $post_id );
        },
        'args' => array(
            'id' => array(
                'validate_callback' => function( $param ) {
                    return is_numeric( $param ) && $param > 0;
                },
                'required' => true,
            ),
        ),
    ) );
}

function get_my_drafts( $request ) {
    $user_id = get_current_user_id();

    $drafts = get_posts( array(
        'author' => $user_id,
        'post_status' => 'draft',
        'posts_per_page' => 20,
        'orderby' => 'modified',
        'order' => 'DESC',
    ) );

    return rest_ensure_response( $drafts );
}

function update_post( $request ) {
    $post_id = $request->get_param( 'id' );
    $title = sanitize_text_field( $request->get_param( 'title' ) );
    $content = wp_kses_post( $request->get_param( 'content' ) );

    $updated = wp_update_post( array(
        'ID' => $post_id,
        'post_title' => $title,
        'post_content' => $content,
    ) );

    if ( is_wp_error( $updated ) ) {
        return $updated;
    }

    return rest_ensure_response( array(
        'success' => true,
        'message' => '文章已更新。',
    ) );
}

通过遵循这些最佳实践,您可以构建出安全、高效且易于维护的权限系统,确保您的WordPress插件或主题能够正确处理各种用户权限场景,同时提供良好的用户体验。