How to Create Custom Taxonomy in WordPress



Taxonomy is a feature in WordPress to group content like posts. Category and tags are in-built taxonomy to group posts in WordPress. WordPress allows us to create own custom taxonomies. So here we are going to see about how to create custom taxonomy in WordPress.

Register Taxonomy

register_taxonomy() is a function to add and register our own custom taxonomy in WordPress. So we need to hook this function to the init action in functions.php file.

Following is an example code for creating custom hierarchical taxonomy Brands. Slug option value will be used in url to access taxonomy posts.

/*
* creating custom taxonomy 'Brands'
*/
function create_custom_taxonomy_brands() {
$labels = array(
'name' => _x( 'Brands', 'taxonomy general name' ),
'singular_name' => _x( 'Brand', 'taxonomy singular name' ),
'search_items' =>  __( 'Search Brands' ),
'all_items' => __( 'All Brands' ),
'parent_item' => __( 'Parent Brand' ),
'parent_item_colon' => __( 'Parent Brand:' ),
'edit_item' => __( 'Edit Brand' ),
'update_item' => __( 'Update Brand' ),
'add_new_item' => __( 'Add New Brand' ),
'new_item_name' => __( 'New Brand Name' ),
'menu_name' => __( 'Brands' ),
);

register_taxonomy('brands', 'post', array(
'labels' => $labels,
'rewrite' => array(
'slug' => 'brands',
'hierarchical' => true
)
));
}
add_action( 'init', 'create_custom_taxonomy_brands', 0 );

We have added this taxonomy for posts,so you can see Brands under posts in WordPress menu. Now you can add taxonomy terms under this taxonomy to group posts.

How to Create Custom Taxonomy in WordPress
How to Create Custom Taxonomy in WordPress

By default your custom taxonomies use the archive.php template to display posts. You can create a custom archive display for these by creating taxonomy-{taxonomy-slug}.php template page.

Hope this tutorial will help you to create custom taxonomy in WordPress.