Creating a Custom Taxonomy in WordPress
Custom Code Solution
This code creates a custom taxonomy that you can use to organize your posts or custom post types. Place this code in your theme's functions.php
file or in a site-specific plugin.
Basic taxonomy registration code for a 'Genre' taxonomy:
function register_genre_taxonomy() {
$labels = array(
'name' => 'Genres',
'singular_name' => 'Genre',
'menu_name' => 'Genres',
'all_items' => 'All Genres',
'edit_item' => 'Edit Genre',
'add_new_item' => 'Add New Genre'
);
$args = array(
'labels' => $labels,
'hierarchical' => true, // Set to false for tags-like behavior
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_rest' => true, // Enable Gutenberg editor support
'query_var' => true,
'rewrite' => array('slug' => 'genre')
);
register_taxonomy('genre', 'post', $args);
}
add_action('init', 'register_genre_taxonomy');
Advanced Version
This extended version includes a custom taxonomy for multiple post types with additional features:
function register_custom_taxonomy() {
// Change these values to match your needs
$taxonomy_name = 'genre';
$taxonomy_labels = array(
'name' => 'Genres',
'singular_name' => 'Genre'
);
$post_types = array('post', 'custom_post_type'); // Add your post types here
$args = array(
'labels' => $taxonomy_labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_rest' => true,
'query_var' => true,
'rewrite' => array(
'slug' => $taxonomy_name,
'with_front' => true,
'hierarchical' => true
),
'capabilities' => array(
'manage_terms' => 'manage_categories',
'edit_terms' => 'manage_categories',
'delete_terms' => 'manage_categories',
'assign_terms' => 'edit_posts'
)
);
register_taxonomy($taxonomy_name, $post_types, $args);
}
add_action('init', 'register_custom_taxonomy');
Important Notes
- After adding the code, visit Settings > Permalinks and click "Save Changes" to flush rewrite rules
- Set
hierarchical
to true
for category-like behavior or false
for tag-like behavior
- Change the taxonomy name, labels, and post types to match your needs
- The
show_in_rest
parameter enables Gutenberg editor support
Plugin Alternative
If you prefer a plugin solution, these options are reliable:
-
Custom Post Type UI - User-friendly interface for creating taxonomies
-
Pods - Advanced content type and field management
Both plugins provide GUI interfaces for creating custom taxonomies without coding.
Usage Example
After registration, you can assign terms to posts using:
wp_set_object_terms($post_id, 'Mystery', 'genre');
Query posts by taxonomy:
$args = array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'genre',
'field' => 'slug',
'terms' => 'mystery'
)
)
);
$query = new WP_Query($args);