Adding Categories And Post Tags Boxes For Custom Post Type In WordPress

Categories and Post Tags boxes are built-in meta boxes that have been already registered in WordPress. We can use them not only for default posts or pages but also for custom post types as well in WordPress. And this can be done easily with argument taxonomies of register_post_type() function when registering new custom post type.

In this example, I'll register a new post type called "demo" with categories and post tags boxes:

add_action('init', 'demo_register_post_type');

function demo_register_post_type() {
    register_post_type('demo', array(
        'labels' => array(
            'name' => 'Demos',
            'singular_name' => 'Demo',
            'add_new' => 'Add new demo',
            'edit_item' => 'Edit demo',
            'new_item' => 'New demo',
            'view_item' => 'View demo',
            'search_items' => 'Search demos',
            'not_found' => 'No demos found',
            'not_found_in_trash' => 'No demos found in Trash'
        ),
        'public' => true,
        'supports' => array(
            'title',
            'excerpt'
        ),
        'taxonomies' => array('category', 'post_tag') // this is IMPORTANT
    ));
}

The taxonomies is an array of registered taxonomies that will be used with this post type. The taxonomy for categories is category and for post tags is post_tag. Both of them are automatically registered, and we can use them without re-defining.

Sometimes, your blog has registered a custom post type already, and you don't want to search in a bunch of code just to find out where the register_post_type() function to add a small line for categories and post tags boxes. To solve this problem, you can add them (categories and post tags boxes) later using register_taxonomy_for_object_type() function like this:

add_action('init', 'demo_add_default_boxes');

function demo_add_default_boxes() {
    register_taxonomy_for_object_type('category', 'demo');
    register_taxonomy_for_object_type('post_tag', 'demo');
}
Note that all these functions have to be called with init action hook. Otherwise, the custom post type is still registered, but no categories or post tags boxes.

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2024 Deluxe Blog Tips. All rights reserved.

My products: Meta Box | Slim SEO