Skip to content

Custom Taxonomies – Organizing Your Custom Posts

_ Just like posts can be categorized into Categories and Tags, custom post types can be grouped using Custom Taxonomies. Taxonomies help organize content by adding genres, topics, or any categorization you need.

Step 1: Define the custom Taxonomies

Let's say we want to categorize our movies by Genre. Here’s how you can register a custom taxonomy for that:

php
function my_noob_theme_register_movie_genre_taxonomy() {
    $labels = array(
        'name'              => _x( 'Genres', 'taxonomy general name', 'mynoobtheme' ),
        'singular_name'     => _x( 'Genre', 'taxonomy singular name', 'mynoobtheme' ),
        'search_items'      => __( 'Search Genres', 'mynoobtheme' ),
        'all_items'         => __( 'All Genres', 'mynoobtheme' ),
        'parent_item'       => __( 'Parent Genre', 'mynoobtheme' ),
        'parent_item_colon' => __( 'Parent Genre:', 'mynoobtheme' ),
        'edit_item'         => __( 'Edit Genre', 'mynoobtheme' ),
        'update_item'       => __( 'Update Genre', 'mynoobtheme' ),
        'add_new_item'      => __( 'Add New Genre', 'mynoobtheme' ),
        'new_item_name'     => __( 'New Genre Name', 'mynoobtheme' ),
        'menu_name'         => __( 'Genres', 'mynoobtheme' ),
    );

    $args = array(
        'hierarchical'      => true, // Make it behave like categories
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array( 'slug' => 'genre' ),
    );

    register_taxonomy( 'genre', array( 'movie' ), $args );
}
add_action( 'init', 'my_noob_theme_register_movie_genre_taxonomy' );
  • register_taxonomy(): This function registers a custom taxonomy (in this case, “Genre”) for the "Movies" post type.
  • hierarchical: If set to true, the taxonomy behaves like categories. If false, it behaves like tags.

Step 2: Displaying Custom Taxonomies 🎭

After creating your custom taxonomy, let’s display the genres for each movie. Update your single movie template (single-movie.php) to include the taxonomy terms:

php
<?php get_header(); ?>

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

    <div class="movie-content">
        <?php the_content(); ?>

        <div class="movie-genres">
            <strong>Genres: </strong>
            <?php
            $terms = get_the_terms( get_the_ID(), 'genre' );
            if ( ! empty( $terms ) ) {
                foreach ( $terms as $term ) {
                    echo '<a href="' . get_term_link( $term ) . '">' . $term->name . '</a> ';
                }
            }
            ?>
        </div>
    </div>

<?php get_footer(); ?>
  • get_the_terms(): Fetches the genres (or any taxonomy terms) assigned to the current post.
  • get_term_link(): Generates the URL to the term’s archive page.

Now, when you visit a movie post, it’ll display its assigned genres. 🎬📂

Built by noobs, for noobs, with love 💻❤️