Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 68 ยท Custom Post Types, Taxonomies and Fields

Custom Taxonomies

Group content with custom taxonomies: register_taxonomy(), hierarchical vs flat, the terms API, taxonomy templates, term meta and default terms explained.

A taxonomy is a way of grouping content. WordPress has two built in: categories, which are hierarchical, and tags, which are flat. Each individual label inside a taxonomy, such as "Fantasy" or "Tutorial", is called a term. Custom taxonomies let you invent your own grouping for any post type: a "Genre" for books, a "Skill" for portfolio projects, a "Venue" for events.

A taxonomy is more than a text field. WordPress builds an admin screen to manage terms, a box in the editor to pick them, archive URLs such as /genre/fantasy/, REST routes and query support. This lesson covers how to register a taxonomy, the difference between hierarchical and flat ones, the terms API, templates, term meta and default terms.

The real functions only run inside WordPress, so real code below is read-only. The runnable examples are plain-PHP stand-ins over SQLite with tables shaped like WordPress's term tables. They show the data model, not core code.

Registering a taxonomy

Use register_taxonomy() on the init hook. It takes the taxonomy key, the post types it applies to, and an array of arguments:

PHP
<?php
function acme_register_genre_taxonomy(): void {
    register_taxonomy( 'genre', [ 'book' ], [
        'labels' => [
            'name'          => 'Genres',
            'singular_name' => 'Genre',
            'add_new_item'  => 'Add New Genre',
            'search_items'  => 'Search Genres',
        ],
        'public'            => true,
        'hierarchical'      => false,
        'show_in_rest'      => true,
        'show_admin_column' => true,
        'rewrite'           => [ 'slug' => 'genre' ],
    ] );
}
add_action( 'init', 'acme_register_genre_taxonomy' );

Key points:

  • The key (genre) may contain lowercase letters, numbers, dashes and underscores and can be at most 32 characters long. Like post types, generic keys can clash with other plugins, so prefix them when in doubt.
  • The object type is a post type key or a list of them. You can attach a taxonomy to several post types, or add one later with register_taxonomy_for_object_type().
  • show_in_rest must be true for the taxonomy panel to appear in the block editor and for REST access.
  • show_admin_column adds a column with the post's terms to the list screen, which editors appreciate.
  • rewrite sets the URL base. As with post types, new rules need a one-time refresh of permalinks (see permalinks and rewrite rules).

Register the taxonomy on the same init callback or an earlier one than the post type, or pass the post type key anyway. WordPress accepts a taxonomy for a post type that is registered later, so the order inside init rarely matters.

Hierarchical or flat?

The hierarchical argument chooses the style:

Hierarchical (true) Flat (false, the default)
Behaves like Categories Tags
Terms can have a parent Yes No
Editor interface Checkbox list Free-text box with suggestions
Good for Fixed structures: "Fiction, then Fantasy" Open-ended labels: "dragons, magic"

Choose hierarchical when the set of terms is controlled by editors and has a natural tree. Choose flat when authors will create labels as they write. You cannot change this cleanly later without migrating the terms, so decide early.

How terms are stored

Terms live in three tables that you saw in the schema lesson, plus a fourth for term meta:

  • wp_terms holds the name and slug.
  • wp_term_taxonomy says which taxonomy a term belongs to, who its parent is, and how many objects use it (count).
  • wp_term_relationships links an object (usually a post ID) to a term_taxonomy_id.
  • wp_termmeta stores custom fields for terms.
erDiagram
    wp_posts ||--o{ wp_term_relationships : "object_id"
    wp_term_taxonomy ||--o{ wp_term_relationships : "term_taxonomy_id"
    wp_terms ||--|| wp_term_taxonomy : "term_id"
    wp_terms ||--o{ wp_termmeta : "term_id"
    wp_terms {
        bigint term_id
        string name
        string slug
    }
    wp_term_taxonomy {
        bigint term_taxonomy_id
        string taxonomy
        bigint parent
        bigint count
    }
    wp_term_relationships {
        bigint object_id
        bigint term_taxonomy_id
    }

A term row, its taxonomy row and the relationship rows that attach it to posts.

Splitting names from taxonomy rows is a historical design. Remember the vocabulary: a term ID identifies a name, a term taxonomy ID identifies "this name in this taxonomy". Relationships use the second one. In most code you pass term IDs or slugs and let WordPress translate.

The terms API

These are the functions you will use in plugins and themes:

PHP
<?php
// Create a term. Returns [ 'term_id' => ..., 'term_taxonomy_id' => ... ]
// or a WP_Error (for example if the term already exists).
$result = wp_insert_term( 'Fantasy', 'genre', [
    'slug'        => 'fantasy',
    'description' => 'Stories with magic and invented worlds.',
] );

if ( is_wp_error( $result ) ) {
    // $result->get_error_code() might be 'term_exists'
}

// Attach terms to a post. By default this REPLACES the post's terms.
wp_set_object_terms( $post_id, [ 'fantasy', 'adventure' ], 'genre' );

// Append instead of replacing.
wp_set_object_terms( $post_id, [ 'classic' ], 'genre', true );

// Read them back. Returns an array of WP_Term objects, false if there are
// none, or a WP_Error if the taxonomy does not exist.
$terms = get_the_terms( $post_id, 'genre' );

if ( $terms && ! is_wp_error( $terms ) ) {
    foreach ( $terms as $term ) {
        echo esc_html( $term->name );
    }
}

// All terms of a taxonomy, for example for a filter menu.
$all = get_terms( [ 'taxonomy' => 'genre', 'hide_empty' => false ] );

Three details save time:

  • wp_set_object_terms() accepts term IDs (integers) or names/slugs (strings). Strings that do not exist yet are created for you, which is convenient but can create typos as new terms. For hierarchical taxonomies always pass IDs, because names are ambiguous when the same name appears under different parents.
  • Always check get_the_terms() with both a truthiness test and is_wp_error(). The three possible return types surprise many developers.
  • get_term_by( 'slug', 'fantasy', 'genre' ) finds one term, and get_the_term_list() prints a ready-made list of links.

Printing term names in HTML needs escaping, as always. See escaping output.

A term store you can run

This stand-in creates the three term tables in SQLite and mimics wp_insert_term(), wp_set_object_terms() and get_the_terms(). It recounts term usage after each change, like the count column does in WordPress.

PHP A term relationship store over SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Post 13 has no terms, so get_the_terms() gives false, the same value real WordPress returns. Replacing terms (the default) dropped Fantasy and Adventure from post 10, and the counts were recomputed. Appending kept Classic and added Adventure.

Hierarchy and templates

Hierarchical taxonomies store a parent term ID. To show a tree you load the terms and group them by parent. Archive pages follow the template hierarchy: for a term "fantasy" in the genre taxonomy WordPress tries taxonomy-genre-fantasy.php, then taxonomy-genre.php, then taxonomy.php, then archive.php, and finally index.php. Category and tag archives have their own names such as category-fantasy.php.

PHP A term tree and taxonomy template candidates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The nested <ul> is what a hierarchical term list looks like in a theme. WordPress offers wp_list_categories() and wp_terms_checklist() for the same job.

Term meta and default terms

Since WordPress 4.4 terms can have custom fields, stored in wp_termmeta. The functions mirror the post meta ones, with term_meta in the name:

PHP
<?php
update_term_meta( $term_id, 'accent_color', '#7a3cff' );
$color = get_term_meta( $term_id, 'accent_color', true );

This is a good place for a term image or a color. Custom fields covers the single-versus-array return and sanitizing, which work the same way here.

A default term is applied when a post is saved without any term in that taxonomy. Pass default_term to register_taxonomy():

PHP
<?php
register_taxonomy( 'genre', [ 'book' ], [
    'hierarchical' => true,
    'show_in_rest' => true,
    'default_term' => [
        'name' => 'Uncategorized Genre',
        'slug' => 'uncategorized-genre',
    ],
] );

WordPress creates that term the first time it is needed. Use it when every item must have at least one term, so templates and queries never meet an empty case.

To fetch posts by term in a query, use tax_query, covered in meta queries and taxonomy queries.

Common mistakes

  • Forgetting show_in_rest. The editor shows no term panel.
  • Treating get_the_terms() as always an array. It can be false or a WP_Error.
  • Passing names to a hierarchical taxonomy. Pass term IDs so the right branch is used.
  • Creating a taxonomy when meta would do. Use a taxonomy when you need archives, grouping and filtering; use meta for a plain value.
  • Forgetting to refresh permalinks. New archive URLs return a 404 until the rules are flushed once.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between a hierarchical and a flat taxonomy?

    hierarchical true behaves like categories with parent terms and checkboxes. The default false behaves like tags.
  2. 2. What does wp_set_object_terms( $post_id, [ 'classic' ], 'genre' ) do with the post's existing genre terms?

    Without the fourth argument set to true the terms are replaced. Pass true to append.
  3. 3. What can get_the_terms() return?

    It returns term objects, false if the object has none, or a WP_Error when the taxonomy does not exist, so check both cases.
  4. 4. Which table connects a post to a term's taxonomy row?

    wp_term_relationships stores pairs of object_id and term_taxonomy_id.
  5. 5. Which template file is the most specific for the term "fantasy" in the genre taxonomy?

    The hierarchy tries taxonomy-{taxonomy}-{term}.php first, then taxonomy-{taxonomy}.php, then taxonomy.php.

Summary

  • A taxonomy groups content; its labels are terms. Register one with register_taxonomy() on init.
  • Hierarchical taxonomies behave like categories, flat ones like tags; choose early.
  • Terms use wp_terms, wp_term_taxonomy, wp_term_relationships and wp_termmeta.
  • wp_insert_term() creates terms, wp_set_object_terms() attaches them (replacing by default), and get_the_terms() reads them back as an array, false or a WP_Error.
  • Archives use taxonomy-{taxonomy}-{term}.php, then taxonomy-{taxonomy}.php, then taxonomy.php.
  • Term meta stores extra values; default_term guarantees a fallback term.
  • The runnable examples are stand-ins that model the data, not core code.

Next: Custom Fields and Post Meta