WordPress Taxonomy

A taxonomy in WordPress is a way to group related content together. It provides a structured method for organizing posts, pages, or custom post types by categories, tags, or custom-defined groups.

Built-in Taxonomies

WordPress includes two default taxonomies for blog posts:

TaxonomyDescription
categoryHierarchical (like folders)
post_tagNon-hierarchical (like keywords)

Custom Taxonomies

You can define your own taxonomies to organize custom post types more effectively.

Example: Registering a Custom Taxonomy

function create_book_taxonomy() {
register_taxonomy('genre', 'book', [
'label' => 'Genres',
'hierarchical' => true,
'rewrite' => ['slug' => 'genre'],
'show_ui' => true,
]);
}
add_action('init', 'create_book_taxonomy');

In this example, genre is a custom taxonomy attached to a book post type.

Hierarchical vs Non-Hierarchical

TypeExampleBehavior
HierarchicalCategories, GenresParent-child relationships
Non-hierarchicalTags, Skills, KeywordsFlat structure

How Taxonomies Work with CPTs

  • You can assign multiple taxonomies to a post type.
  • Custom taxonomies appear in the WordPress admin like categories or tags.
  • They integrate with query tools like WP_Query, tax_query, and template tags.

Displaying Taxonomies

  • Template tags: phpCopyEditthe_terms( get_the_ID(), 'genre' );
  • Custom archive templates:
    Create taxonomy-genre.php to control how genre pages look.

Querying Posts by Taxonomy

$args = [
    'post_type' => 'book',
    'tax_query' => [
        [
            'taxonomy' => 'genre',
            'field' => 'slug',
            'terms' => 'science-fiction',
        ],
    ],
];
$query = new WP_Query($args);

Summary

FeatureDescription
PurposeGroup and organize content
Built-incategory, post_tag
Custom Examplesgenre, location, skill
Structure OptionsHierarchical or non-hierarchical
Used WithPosts, Pages, or Custom Post Types