Give a Role Full Control of One Post Type Only
Gives a custom post type its own permissions and lets a chosen role (for example Author) manage it fully, including others' items, without extra rights elsewhere.
Opens WPIDE on
Code
// Post type, its capability names, and the roles that manage it.
$wpide_cpt_caps = array(
'post_type' => 'event',
'singular' => 'event',
'plural' => 'events',
'roles' => array( 'administrator', 'editor', 'author' ),
);
add_filter( 'register_post_type_args', function ( $args, $post_type ) use ( $wpide_cpt_caps ) {
if ( $wpide_cpt_caps['post_type'] === $post_type ) {
$args['capability_type'] = array( $wpide_cpt_caps['singular'], $wpide_cpt_caps['plural'] );
$args['map_meta_cap'] = true;
}
return $args;
}, 10, 2 );
add_filter( 'user_has_cap', function ( $allcaps, $caps, $args, $user ) use ( $wpide_cpt_caps ) {
if ( ! $user instanceof WP_User || ! array_intersect( (array) $user->roles, $wpide_cpt_caps['roles'] ) ) {
return $allcaps;
}
$object = get_post_type_object( $wpide_cpt_caps['post_type'] );
if ( ! $object ) {
return $allcaps;
}
// Grant every primitive capability of this post type (edit_events, publish_events, ...).
foreach ( (array) $object->cap as $meta => $primitive ) {
if ( ! in_array( $meta, array( 'edit_post', 'read_post', 'delete_post' ), true ) ) {
$allcaps[ $primitive ] = true;
}
}
return $allcaps;
}, 10, 4 );
Notes
Administrators keep full access. The permissions are granted while the snippet runs, so nothing is written to the database.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.