Adding a Custom Taxonomy in WordPress
Custom Code Solution
This code creates a new custom taxonomy called "Topics" for your blog posts. Place this code in your theme's functions.php
file or in a site-specific plugin:
Register the custom taxonomy:
function create_topics_taxonomy() {
$labels = array(
'name' => 'Topics',
'singular_name' => 'Topic',
'search_items' => 'Search Topics',
'all_items' => 'All Topics',
'parent_item' => 'Parent Topic',
'parent_item_colon' => 'Parent Topic:',
'edit_item' => 'Edit Topic',
'update_item' => 'Update Topic',
'add_new_item' => 'Add New Topic',
'new_item_name' => 'New Topic Name',
'menu_name' => 'Topics'
);
$args = array(
'labels' => $labels,
'hierarchical' => true, // Set to false if you want tag-like behavior
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_rest' => true, // Enable Gutenberg support
'query_var' => true,
'rewrite' => array('slug' => 'topic')
);
register_taxonomy('topic', array('post'), $args);
}
add_action('init', 'create_topics_taxonomy');
Code Customization
To modify this code for your needs:
- Change 'topic' to your desired taxonomy name
- Adjust the 'labels' array text
- Change the 'slug' in rewrite array
- Modify 'hierarchical' to false if you want tag-like behavior instead of categories
Plugin Alternative
If you prefer using a plugin, here are reliable options:
-
Custom Post Type UI - User-friendly interface for creating taxonomies
-
Pods - Advanced content type and field management
Usage After Implementation
Once implemented, you can:
- Find "Topics" in your WordPress admin menu
- Add new topics like regular categories
- Assign topics to posts while editing
- Filter posts by topics in the admin area
- Use WordPress functions like
get_terms()
to display topics on your site
Query Example
To display posts from a specific topic:
$args = array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'topic',
'field' => 'slug',
'terms' => 'your-topic-slug'
)
)
);
$query = new WP_Query($args);