How to create a custom taxonomy template in WordPress?

WordPress is a powerful and flexible content management system that allows users to create and manage various types of content. One key feature that makes WordPress so versatile is its taxonomy system. Taxonomies help organize content meaningfully, making it easier for users to find and interact with content on your website. While WordPress comes with built-in taxonomies like categories and tags, creating custom taxonomies can significantly enhance your site's functionality and user experience. In this guide, we'll walk through the process of creating and using custom taxonomies in WordPress, complete with an example.

What is a Custom Taxonomy?

A taxonomy in WordPress is a way to group and categorize posts and other content types. A custom taxonomy is a user-defined grouping method that allows you to create custom groupings beyond the default categories and tags. For instance, if you run a book review site, you might want to categorize your reviews by genre, author, or publisher.

Why Use Custom Taxonomies?

Custom taxonomies help to:

  • Improve site organization
  • Enhance content discoverability
  • Enable better content filtering
  • Provide more precise search capabilities
  • Tailor the content structure to fit specific needs

Creating a Custom Taxonomy: Step-by-Step Guide

Let's create a custom taxonomy called "Genre" for a custom post type "Books."

Step 1: Register a Custom Post Type

First, we need a custom post type to associate our custom taxonomy. We'll create a custom post type called "Books."

Add the following code to your theme's functions.php file or in a custom plugin:

function create_books_post_type() {
    $labels = array(
        'name'               => 'Books',
        'singular_name'      => 'Book',
        'menu_name'          => 'Books',
        'name_admin_bar'     => 'Book',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New Book',
        'new_item'           => '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 found in Trash.'
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array('slug' => 'book'),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => null,
        'supports'           => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments')
    );

    register_post_type('book', $args);
}

add_action('init', 'create_books_post_type');

Step 2: Register the Custom Taxonomy

Next, we’ll register the custom taxonomy "Genre" for our "Books" post type.

Add the following code to the functions.php file or in your custom plugin:

function create_genre_taxonomy() {
    $labels = array(
        'name'              => 'Genres',
        'singular_name'     => 'Genre',
        'search_items'      => 'Search Genres',
        'all_items'         => 'All Genres',
        'parent_item'       => 'Parent Genre',
        'parent_item_colon' => 'Parent Genre:',
        'edit_item'         => 'Edit Genre',
        'update_item'       => 'Update Genre',
        'add_new_item'      => 'Add New Genre',
        'new_item_name'     => 'New Genre Name',
        'menu_name'         => 'Genre'
    );

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

    register_taxonomy('genre', array('book'), $args);
}

add_action('init', 'create_genre_taxonomy');

Step 3: Assign Terms to Your Custom Taxonomy

After registering your custom taxonomy, you can now add terms to it. Go to the WordPress admin dashboard to see a new menu item for "Genres" under the "Books" post type. You can add, edit, and delete genres as needed.

Step 4: Display Custom Taxonomies in Your Theme

You need to modify your theme files to display the custom taxonomy terms on your single book post page.

Add the following code to the single-book.php file in your theme (create the file if it doesn’t exist):

<?php get_header(); ?>

<?php
while ( have_posts() ) : the_post(); ?>

    <h1><?php the_title(); ?></h1>
    <div><?php the_content(); ?></div>

    <div class="book-genres">
        <h2>Genres</h2>
        <?php
        $terms = get_the_terms( $post->ID, 'genre' );
        if ( $terms && ! is_wp_error( $terms ) ) :
            foreach ( $terms as $term ) {
                echo '<span>' . $term->name . '</span> ';
            }
        endif;
        ?>
    </div>

<?php endwhile; ?>

<?php get_footer(); ?>

This code snippet fetches and displays the genres associated with a book.

Conclusion

Custom taxonomies in WordPress offer a powerful way to organize your content beyond the default categories and tags. By following the steps outlined in this guide, you can create custom taxonomies that suit your specific needs, providing better content organization and improved user experience on your website. Whether you run a blog, an e-commerce site, or a complex content platform, custom taxonomies can help you manage and display your content more effectively.

Happy coding!