By default the WordPress “category” taxonomy is only registered to standard posts, but what if you wanted to create categories that could be associated with multiple post types on your site? Perhaps you have a custom post type that you also want to categorize?
Enable Categories for Existing Custom Post Types
Enabling the default category taxonomy for use with other existing custom post types is very easy. All you need to do is use the WordPress core register_taxonomy_for_object_type function like such:
add_action( 'init', function() {
register_taxonomy_for_object_type( 'category', 'YOUR_POST_TYPE' );
}, 50 );
Simply change the “YOUR_POST_TYPE” text to match the name of your custom post type. As you can see we are actually running this function on the “init” hook and with a later priority of 50. The reason we do this is because custom post types are usually and should be registered on the init hook and so we want to make sure our code runs when the post type has already been registered.
Enable Categories for New Custom Post Types
If you are registering a new post type on your site and want to enable categories for it you can do so by using the “taxonomies” parameter in your register_post_type
function. Below is an example:
register_post_type( 'book', [
'public' => true,
'label' => __( 'Books', 'textdomain' ),
'menu_icon' => 'dashicons-book',
'taxonomies' => [ 'category' ],
] );
Using the Post Types Unlimited Plugin
If you are adding your post type using our awesome Post Types Unlimited plugin then it’s of course even easier! When adding your post type simply scroll down and locate the “Taxonomies” field and from here you can easily check the taxonomies you want enabled for your custom post type:
In fact, with our Post Types Unlimited plugin you can also register new taxonomies so rather then “polluting” the standard WordPress categories taxonomy you could always register your own taxonomy for use and then assign it to whatever post type you want it to work with. In my opinion this is usually the better option rather then assigning the default categories to your custom post types as you will have more control over your taxonomy.