Add a Custom Taxonomy to a Custom Post Type

We’ve previously gone over how to setup a custom post type and output the data, but now we’ll take that guide a step further and go over how to setup a custom post type with a custom taxonomy. If you are wondering what a taxonomy is, then you can think of it as a way to make a custom grouping of data much in the same way that a regular wordpress post has a grouping of categories or tags that you can add to a post.

In the example we’ll go over below, we will be making a “Case Studies” custom post type and we will then add a “Services” taxonomy. This example was setup like this so that we would be able to create individual case studies and be able to tag them with specific services using the custom taxonomy. This allows us to do cool stuff like filter or sort by the “Case Studies” that utilized a specific service from our “Services” taxonomy. We can also output the list of all used services on each individual case study page. Now, let’s get started!

Creating the Custom Post Type

This is just the setup of the custom post type for Case Studies. You can add this code right to your child theme’s functions.php file. In fact, all of the code in this guide will be added right to the functions.php file.

Creating a Custom Taxonomy

This code will setup the custom taxonomy and it also links the taxonomy to our previously created custom post type. The linking happens in with the ‘register_taxonomy’ function below.

Custom Taxonomy UI

Here is what the finished product will look like on our backend admin area.

The “Services” taxonomy will appear on our custom post type’s menu section:

custom taxonomy in the admin menu

It will show on the listing page of the custom post type items where it will show the individual terms for each:

custom taxomony in listings

Finally, you’ll see it in the editor of an individual custom post type item where you’d normally see the ‘categories’ and ‘tags’ sections. You add in the individual taxonomy terms here:

custom taxonomy in the CPT editor

Your Custom Taxonomy

That’s all the code you’ll need, but most you likely won’t want to use this specific ‘case study / services’ combination. Think over your project’s data structure needs and if a CPT with a custom taxonomy is what you need, then just modify the above code to accommodate it. The core code will all be the same, you just will need to update all the assigned labels and match the slugs properly when registering the taxonomy. Now go try it out for yourself!

Speak Your Mind

*