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:
Taxonomy | Description |
---|---|
category | Hierarchical (like folders) |
post_tag | Non-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 abook
post type.
Hierarchical vs Non-Hierarchical
Type | Example | Behavior |
---|---|---|
Hierarchical | Categories, Genres | Parent-child relationships |
Non-hierarchical | Tags, Skills, Keywords | Flat 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: phpCopyEdit
the_terms( get_the_ID(), 'genre' );
- Custom archive templates:
Createtaxonomy-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
Feature | Description |
---|---|
Purpose | Group and organize content |
Built-in | category , post_tag |
Custom Examples | genre , location , skill |
Structure Options | Hierarchical or non-hierarchical |
Used With | Posts, Pages, or Custom Post Types |