Wordpress:允许自定义角色仅编辑自定义帖子类型(不是常规帖子)

问题描述 投票:0回答:1

我被困在一个可能非常简单的问题上。我使用以下代码注册了一个 CPT 来定义特殊功能:

$args = [
        "label" => "Tracts",
        "description" => "",
        "public" => true,
        "publicly_queryable" => true,
        "show_ui" => true,
        "show_in_nav_menus" => true,
        "map_meta_cap" => true,
        "rewrite" => [ "slug" => "tract", "with_front" => true ],
        "query_var" => true,
        "supports" => [ "title", "editor", "thumbnail", "excerpt" ],
        'capabilities' => array(
            'edit_posts' => 'edit_tracts',
            'edit_others_posts' => 'edit_others_tracts', 
            'delete_posts' => 'delete_tracts',
            'publish_posts' => 'publish_tracts', 
        )
    ];

    register_post_type( "tract", $args );

然后我要注册一个新角色。该角色只需能够查看和编辑此自定义帖子类型。我无法让他们看到常规帖子。

add_role('land_editor', 'Land Editor', array(
    'read' => true,
    'edit_tracts' => true,
    'edit_others_tracts' => true, 
    'delete_tracts' => true,
    'publish_tracts' => true,
));

使用此代码,我的角色可以执行我需要执行的所有操作(他们可以查看 CPT、编辑它等),除了在自定义帖子类型中添加新帖子之外。每当我单击“添加新”时,我都会进入“抱歉,您无权访问此”页面。但是,当我将“edit_posts”添加到新角色的功能数组时,我可以突然添加自定义帖子类型的新帖子。但是,这也使用户能够查看和添加所有其他帖子类型的新内容,因此我不能这样做。关于为什么 edit_tracts 不允许我添加新的单张有什么见解吗?

php wordpress
1个回答
1
投票
function add_custom_caps() {
    
   $roles = get_role('land_editor');
    foreach($roles as $the_role) {
        $role = get_role($the_role);
        $role->add_cap( 'read' );
        $role->add_cap( 'read_tract');
        $role->add_cap( 'read_private_tract' );
        $role->add_cap( 'edit_tract' );
        $role->add_cap( 'edit_others_tract' ); 
        $role->add_cap( 'edit_published_tract' );
        $role->add_cap( 'publish_tract' );
        $role->add_cap( 'delete_others_tract' ); 
        $role->add_cap( 'delete_private_tract' );
        $role->add_cap( 'delete_published_tract' );
       $role->add_cap( 'edit_published_posts' );
       $role->add_cap( 'published_posts' );
    }
}
add_action('admin_init', 'add_custom_caps', 5 );
© www.soinside.com 2019 - 2024. All rights reserved.