In WordPress, taxonomies are a way to group things together.
In a default WordPress install, there are two types of registered taxonomies, categories and tags.
When developing a plugin that registers a custom post type, you could also register custom taxonomies.
This adds some additional flexibility to your plugin, as it allows your custom post types to
be grouped independently from the default categories or tags. Let's look at how this
works and what you need to register a custom taxonomy. You might think that the two taxonomies
that come with WordPress are enough, but there are times when your plugin might need to group
data in a different way. For example, in a bookstore, you might want to group books by genre,
such as fiction, non-fiction, science fiction, etc. When you register a custom taxonomy for a
specific post type, that taxonomy will only be available to the post type and will appear
associated to the post type in both the admin menu and the edit screens. Let's add a custom
taxonomy to the bookstore plugin you were building in the previous lessons. To register a custom
taxonomy, you can use the register taxonomy function in a similar way that you use the
register post type function. This function requires you to pass in the name of the taxonomy,
the post type that the taxonomy is associated with, and an array of arguments that define the
taxonomy. Similar to the register post type function, the register taxonomy function also
needs to be hooked into the init action. So start by registering the callback to the action.
Then you can create the bookstore register genre taxonomy callback function.
In this function, create the arguments array
and then call the register taxonomy function, passing in the relevant arguments to create the taxonomy.
You could also add this code to the bookstore register book post type function
so that the taxonomy is registered when the book post type is registered.
Once this is added to your bookstore plugin, you'll see a new genre menu in the admin menu
and you'll be able to add genres to your books.
Additionally, once you've added some genres, you'll be able to select from those genres when
you add or edit a book. And just like with regular taxonomies, you will be able to browse
the archive page for each taxonomy and see all the books that are associated with that taxonomy.
To read more about custom taxonomies and how to register them,
visit the taxonomies page in the plugin developer handbook.
It's also a good idea to read the full register taxonomy function reference page in the WordPress
developer documentation, as it contains the full list of all the arguments that can be
passed to the function and what they do.