Add Custom Post Types and Taxonomies in WordPress

Enhancing WordPress functionality often involves creating custom content types. By using register_post_type and register_taxonomy, you can build tailored solutions for your site. Let’s go through the process together.

 

Step 1: Define the Post Type “Books”

We’ll register a new post type named Books using the function below:

function create_books_post_type() {
    $labels = array(
        'name'               => 'Books',
        'singular_name'      => 'Book',
        'menu_name'          => 'Books',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New Book',
        'edit_item'          => 'Edit Book',
        'view_item'          => 'View Book',
        'all_items'          => 'All Books',
        'search_items'       => 'Search Books',
        'not_found'          => 'No Books Found',
        'not_found_in_trash' => 'No Books in Trash',
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'has_archive'        => true,
        'rewrite'            => array('slug' => 'books'),
        'supports'           => array('title', 'editor', 'thumbnail'),
    );

    register_post_type('book', $args);
}
add_action('init', 'create_books_post_type');

Step 2: Create the “Genres” Taxonomy

Now, let’s define a custom taxonomy called Genres for classifying books.

function register_genres_taxonomy() {
    $labels = array(
        'name'               => 'Genres',
        'singular_name'      => 'Genre',
        'search_items'       => 'Search Genres',
        'all_items'          => 'All Genres',
        'edit_item'          => 'Edit Genre',
        'add_new_item'       => 'Add New Genre',
        'new_item_name'      => 'New Genre Name',
        'menu_name'          => 'Genres',
    );

    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'rewrite'           => array('slug' => 'genre'),
    );

    register_taxonomy('genre', 'book', $args);
}
add_action('init', 'register_genres_taxonomy');

 

Your WordPress site is now ready to handle “Books” as a content type, and “Genres” as their categories. This adds a whole new level of content organization.

Final Thoughts

WordPress customization using post types and taxonomies is a powerful way to expand your site. These functions open doors to fully structured and manageable content types.

Further Resources

Leave a Comment

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

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.