如何为WordPress自定义角色设置自定义文章类型edit_published_posts权限为false
你的需求完全可以实现,问题出在自定义文章类型(CPT)注册时的权限映射配置不全,缺少核心参数。
问题原因
默认edit_published_posts权限仅作用于WordPress内置的文章(post)类型,自定义文章类型需要单独定义对应的专属权限规则,并开启元权限映射才能生效。你之前的代码遗漏了edit_published_posts对应的自定义权限声明,也没有开启map_meta_cap参数,导致权限判断逻辑失效。
完整实现代码
1. 修正自定义文章类型注册逻辑
function my_custom_post_type(){ $args = array( 'labels' => array( 'name' => 'my_custom_post_type', ), 'hierarchical' => false, 'public' => true, 'has_archive' => true, 'menu_icon' => 'dashicons-images-alt2', 'supports' => array('title', 'editor', 'thumbnail', 'custom-fields', 'author'), // 开启元权限映射,必填参数 'map_meta_cap' => true, // 补全所有对应权限 'capabilities' => array( 'read' => 'read_my_cpt', 'edit_posts' => 'edit_my_cpts', 'edit_others_posts' => 'edit_others_my_cpts', 'edit_published_posts' => 'edit_published_my_cpts', 'publish_posts' => 'publish_my_cpts', 'delete_posts' => 'delete_my_cpts', 'delete_others_posts' => 'delete_others_my_cpts', 'delete_published_posts' => 'delete_published_my_cpts', ), ); register_post_type('my_custom_post_type', $args); } add_action('init', 'my_custom_post_type');
2. 自定义角色添加与权限分配
注意add_role方法只会写入数据库一次,建议绑定主题/插件激活钩子,避免重复执行产生残留数据:
// 主题激活时执行一次 add_action('after_switch_theme', 'init_custom_role'); // 插件激活时替换为以下钩子 // register_activation_hook(__FILE__, 'init_custom_role'); function init_custom_role() { // 先移除已存在的同名角色,清除旧权限残留 remove_role('custom_role'); // 添加角色,基础权限仅保留后台访问权限 add_role('custom_role', '自定义投稿角色', array( 'read' => true, )); // 分配CPT权限 $role = get_role('custom_role'); // 允许读取CPT内容 $role->add_cap('read_my_cpt', true); // 允许编辑草稿状态的CPT $role->add_cap('edit_my_cpts', true); // 禁止发布CPT $role->add_cap('publish_my_cpts', false); // 禁止编辑已发布的CPT,核心控制参数 $role->add_cap('edit_published_my_cpts', false); // 禁止编辑他人提交的CPT,可选配置 $role->add_cap('edit_others_my_cpts', false); }
验证注意事项
- 配置完成后先切换到管理员账号,执行一次主题切换(切到默认主题再切回来)触发角色初始化逻辑
- 测试账号需要重新登录,清除本地权限缓存
- 如果需要兼容旧数据,可安装权限管理类插件重置全局权限缓存
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

