简体   繁体   中英

Wordpress : Allow custom role to edit ONLY custom post type (not regular posts)

I'm stuck on what is probably a really simple issue. I have a CPT registered using the following code to define special capabilities:

$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 );

I'm then registering a new role. This role needs to ONLY be able to view and edit this custom post type. I can't have them able to see the regular posts.

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

With this code, my role is able to everything I need it to do (they can view the CPT, edit it, etc.) EXCEPT add a new post in the custom post type. Whenever I click 'add new', I get taken to the "sorry, you don't have permission to access this" page. However, when I add 'edit_posts' to the new role's capability array, I can suddenly add new posts of the custom post type. However, this also enables the user to view and add new of all the other post types, so I can't do it like this. Any insight as to why edit_tracts is not allowing me to add new tracts?

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' );
    }
}
add_action('admin_init', 'add_custom_caps', 5 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM