Custom Post Types – Capability Type

I’ve been developing a custom post type plugin for my own purposes and I want to understand capabilities in regards to custom post types a little better before I move forward. Unfortunately the WordPress Codex doesn’t really clear it up for me.

I just don’t understand what capabilities are actually doing in regards to custom post types.

For example, when I create a custom post type called ‘book’ and I use ‘book’ as the capability_type, it generates these 7 primitive capabilities:

[edit_post]          => edit_book
[read_post]          => read_book
[delete_post]        => delete_book
[edit_posts]         => edit_books
[edit_others_posts]  => edit_others_books
[publish_posts]      => publish_books
[read_private_posts] => read_private_books

Now, can I just create any kind of capability I like? For example could I do this:

[random_capability]  => edit_book

So that any user role who has the capability of edit_book can also have permission for random capability?

I’ve tried experimenting with it by creating two custom post types: book and fantasy-book.

I gave book that random_capability and then told fantasy-book to use book as its capability_type. Now, my understanding is that it would pull books capabilities (including random_capability) and give that capability to fantasy-book, correct?

In practice that doesn’t work. I feel like capability_type should be pulling the capabilities of whatever type you give it, or create new capabilities if said type does not exist yet.

If not, then I have no idea how capability_type works and haven’t been able to find anything about this. Anyone have any knowledge regarding this?

Any help is greatly appreciated.

1 Answer
1

I agree with you that the codex isn’t a huge help on this subject. Check out the stuff about capabilities under register_post_type – it needs a serious rewrite.

As I understand it, only page and post can be used in the way you suggest (and in fact post is used by default in the absence of a defined capability type).

Of course, by creating your book version of all the usual caps, you allow yourself to assign capabilities specific to your custom post type, either in your own code or via a plugin such as members.

You can create any capability you like, but I’m not sure you can do it at that stage. What I tend to do, is assign a custom cap to a role:

$role = get_role( 'administrator' );
$role->add_cap( 'access_awesomeness' );

I would probably do this on plugin activation, as caps are written to the DB, so why do it more than once.

Your plugin can then check if the current user has permission to do whatever with it:

if (current_user_can( 'access_awesomeness' )) { ...

You can also use it where you’d add any other permission – for example:

add_menu_page( $page_title, $menu_title, 'access_awesomeness', $menu_slug, $function, $icon_url, $position );

I’m not sure that answers your question entirely, but that’s my 2 cents worth.

Leave a Comment