In the previous article here, I explained how to create a Custom Post Type. In this article I will show you how to create custom taxonomies in WordPress.
What is a Custom Taxonomy?
Taxonomies are a grouping mechanism for the post types in WordPress. For example, you group together categories of posts by creating categories, similarly you can group together custom post types or any existing post type by creating a taxonomy. The names created to group together the posts are called “terms”.
Why do I need a custom taxonomies in WordPress?
Suppose you have a custom post type of news which we created in this article and you want to categorize the news into different sections like world, sports, technology, this is when you need a custom taxonomy. Through a custom taxonomy you can create terms and assign posts under those terms, so that each term can have it’s own page with a list of posts under it
How to create a custom taxonomies in WordPress?
Just like adding a custom post type, all you need to do is add in some code to your functions.php
Here is how the code looks like
function add_news_taxonomy() { register_taxonomy('news_cat', 'news', array( 'hierarchical' => true, 'labels' => array( 'name' => _x( 'News Categories', 'taxonomy general name' ), 'singular_name' => _x( 'News Category', 'taxonomy singular name' ), 'search_items' => __( 'Search News Categories' ), 'all_items' => __( 'All News Categories' ), 'parent_item' => __( 'Parent News Category' ), 'parent_item_colon' => __( 'Parent News Category:' ), 'edit_item' => __( 'Edit News Category' ), 'update_item' => __( 'Update News Category' ), 'add_new_item' => __( 'Add New News Category' ), 'new_item_name' => __( 'New News Category Name' ), 'menu_name' => __( 'News Categories' ), ), 'rewrite' => array( 'slug' => 'news-category', 'with_front' => false, 'hierarchical' => true ), )); } add_action( 'init', 'add_news_taxonomy');
Adding the above will show you the sub-menu item “News Categories”
Here are the things you should pay attention to while create custom taxonomies in WordPress
register_taxonomy('news_cat', 'news', array(
In the line above, the news_cat is the name which will be stored in the database for this taxonomy. It has to be lowercase without any spaces. Underscores are allowed. It cannot exceed 32 characters as well.
“news” is the post type where this custom taxonomy will be added. You can add it to any existing post type or any custom post type you create
For example if you want to add a custom taxonomy to the “post” post type, this would change to
register_taxonomy('news_cat', 'post', array(
The “slug” defines the URL of your custom taxonomy pages. Suppose you create a term called “sports”, the URL of that page would be example.com/news-category/sports/. Again this should not contain spaces and has to be “unique” so that name “conflicts” don’t occur.
'slug' => 'news-category',