What is WordPress Taxonomy and how to create one?

Taxonomy is basically a way to group things together. In WordPress, taxonomy is a way to group some posts or custom post types together. WordPress by default has two popular taxonomies that we use regularly, namely categories and Tags. Link Category and Post formats are two other default taxonomies we’ve got.

You can also use custom taxonomies to create custom groups. For example, you are building a website with a list of movies. You created a custom post type called Movies. You want to be able to add movie Genre and Actors while creating a new movie. You can register a new custom taxonomy called Genre and Actors. This will allow the website visitors to sort the movies list by each Genre or get a list of movies an actor has been part of.

The names for the different groupings in a taxonomy are called terms. For example, using grouping movies by genres, we might call one group “drama”, and another group “thriller”. “Drama” and “thriller” are terms in our taxonomy.

Creating Taxonomy

Now, Let’s see how can we create our own custom taxonomy. We can use the register_taxonomy() function to create a new custom taxonomy. Let’s assume we have got a custom post type named “movie” and we want to create taxonomies under “movie”.

// Register Custom Taxonomy
function gskhanal_custom_taxonomy() {
creating custom taxonomy: genre
//preparing labels
$tax_labels = array(
'name' => _x( 'Genres' ),
'singular_name' => _x( 'Genre' ),
'menu_name' => __( 'Genres' ),
'all_items' => __( 'All Genres' ),
'parent_item' => __( 'Parent Genre' ),
'parent_item_colon' => __( 'Parent Genre:' ),
'new_item_name' => __( 'New Genre' ),
'add_new_item' => __( 'Add New Genre' ),
'edit_item' => __( 'Edit Genre' ),
'update_item' => __( 'Update Genre' ),
'view_item' => __( 'View Genre' ),
'separate_items_with_commas' => __( 'Separate items with commas' ),
'add_or_remove_items' => __( 'Add or remove items' ),
'choose_from_most_used' => __( 'Choose from the most used' ),
'popular_items' => __( 'Popular Items' ),
'search_items' => __( 'Search Genres' ),
'not_found' => __( 'Not Found' ),
//preparing arguments
$tax_args = array(
'labels' => $tax_labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true
// registering custom taxonomy genre
register_taxonomy( 'genre', array( 'movie' ), $tax_args );
add_action( 'init', 'gskhanal_custom_taxonomy', 0 );

You need a good knowledge of custom taxonomy and custom post type if you want to build highly customized content management system (CMS). I hope you enjoyed learning about taxonomies. In the next article I’ll write about how you can display the custom taxonomy you just created. Happy learning 🙂

Leave a comment

Your email address will not be published. Required fields are marked *