Register a custom taxonomy for a post type
WordPress has two built-in taxonomies for posts: categories (hierarchical) and tags (flat). A custom taxonomy works the same way, but you decide what it is called and which post types it belongs to: books by genre, portfolio items by technique, events by city.
Problem: A custom post type needs its own way of grouping entries that is not mixed with the blog categories and tags.
Solution: Register the taxonomy with register_taxonomy() on the init hook and pass the post types it belongs to. Then assign and read terms with wp_set_object_terms() and get_the_terms().
Registering the taxonomy
The example registers a hierarchical genre taxonomy for a book post type:
<?php
add_action( 'init', 'ha_register_genre_taxonomy' );
function ha_register_genre_taxonomy() {
$labels = array(
'name' => __( 'Genres', 'textdomain' ),
'singular_name' => __( 'Genre', 'textdomain' ),
'search_items' => __( 'Search Genres', 'textdomain' ),
'all_items' => __( 'All Genres', 'textdomain' ),
'parent_item' => __( 'Parent Genre', 'textdomain' ),
'edit_item' => __( 'Edit Genre', 'textdomain' ),
'update_item' => __( 'Update Genre', 'textdomain' ),
'add_new_item' => __( 'Add New Genre', 'textdomain' ),
'new_item_name' => __( 'New Genre Name', 'textdomain' ),
'menu_name' => __( 'Genres', 'textdomain' ),
);
register_taxonomy( 'genre', array( 'book' ), array(
'labels' => $labels,
'hierarchical' => true, // true = like categories, false = like tags
'public' => true,
'show_admin_column' => true, // a "Genres" column in the list of books
'show_in_rest' => true, // available in the REST API (and in the Gutenberg editor plugin)
'rewrite' => array( 'slug' => 'genre' ),
) );
}
The taxonomy name (genre) must be lowercase, up to 32 characters, and must not clash with reserved query vars such as category, tag, author or year.
If the post type is registered by a plugin and you add the taxonomy to it from your code, call register_taxonomy_for_object_type( 'genre', 'book' ) after both are registered.
Assigning and reading terms
<?php
// Replace the genres of a book (slugs; terms that do not exist are created)
wp_set_object_terms( $post_id, array( 'fiction', 'thriller' ), 'genre' );
// Add a genre without removing the others
wp_set_object_terms( $post_id, 'classic', 'genre', true );
// Read the genres in a template
$terms = get_the_terms( get_the_ID(), 'genre' );
if ( $terms && ! is_wp_error( $terms ) ) {
echo get_the_term_list( get_the_ID(), 'genre', '<p>Genres: ', ', ', '</p>' );
}
The archive of one term is available at /genre/fiction/ and uses taxonomy-genre.php, taxonomy.php or archive.php from the theme, in this order.
NOTE: After registering a new taxonomy, open Settings → Permalinks and click Save once to rebuild the rewrite rules, otherwise the term archives return 404.