Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.