Skip to content

Custom capability types for custom post types doesn't automatically give administrator capabilities  #79

@bignall

Description

@bignall

If a custom capability type is defined for a custom post type the administrator role doesn't automatically get capabilities for that capability type. I discovered this when I did a fresh install of wordpress that has only my plugin in it, so I must have some plugin that changes that behavior in my old installation.

So I propose adding to the CPT sub generator the following:

A helper class (mine has some other stuff in it too, but this is what's pertinent to this issue):

class Helper {  
    /**
     * Adds all capabilities for a capability type to a role
     * 
     * @param string|array $cap_type the capability type - array allows for specifying 
     *      singular and plural, otherwise plural is constructed by adding an 's' 
     *      to the string
     * @param string $role_name the role name (default: administrator)
     * @return WP_Role
     */
    static function add_caps( $cap_type, $role_name = 'administrator' ) {
        $role = get_role( $role_name );
        if ( is_array( $cap_type ) ) {
            $singular = $cap_type[0];
            $plural = $cap_type[1];
        } else {
            $singular = $cap_type;
            $plural = $cap_type . 's';
        }

        $role->add_cap( 'edit_' . $singular );
        $role->add_cap( 'edit_' . $plural );
        $role->add_cap( 'edit_other_' . $plural );
        $role->add_cap( 'publish_' . $plural );
        $role->add_cap( 'read_' . $singular );
        $role->add_cap( 'read_private_' . $plural );
        $role->add_cap( 'delete_' . $singular );

        return $role;
    }
}

In the generated post type class:

Define the capability type:

       /**
     * Capability type
     * 
     * @var string
     * @since 0.0.0
     */
    const CAPABILITY_TYPE = '<custom capability_type specified>';

In the constructor - parent::__construct args array:

                'capability_type' => self::CAPABILITY_TYPE,

In the hooks method:

        add_action( 'admin_init', array( $this, 'add_caps' ) );

And the add_caps method:

      /**
     * Add capabilities for our custom capability type
     * 
     * @since 0.0.0
     * @return void
     */
    public function add_caps() {
        Helper::add_caps( self::CAPABILITY_TYPE );
    }

I don't remember if the generator has an option for adding a custom capability_type in the args for the CPT, but if not that could be added and this code generated if a custom capability_type is selected.

This would give the user a starting point for their custom capabilities.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions