Why a Custom Taxonomy Might Not Be Returned in WordPress

When creating a plugin or theme in WordPress there might come a time when you need to use custom taxonomies. As well as creating the taxonomies in the first place, you might need to work with them in some other way too; be this outputting them in a list, or programmatically assign a post to one or more taxonomies.

Either way you’ll be best off using the built-in WordPress functions such as get_taxonomies(), term_exists(), wp_insert_term() and others to do the task of setting up the relationships in the database for you.

The Problem

I faced a problem the other day where, within a WordPress automated task, I needed to assign a post to multiple taxonomies.

Unfortunately the above didn’t work and all I got was an error about how I was using an invalid taxonomy. I know it wasn’t invalid because I was registering it fine, was able to use it ok within the WordPress backend, and I could see references to it in the database.

So why would it claim that it was invalid? Allow me to explain…

The Investigation

The first step I took was to see what taxonomies WordPress thought were valid. I used the function get_taxonomies() like so:

And sure enough, in the list that was output, my custom taxonomy wasn’t included.

This got me thinking that maybe my taxonomy did exist, but it was the order in which I was doing things that was wrong. Both the registration of the custom taxonomy, and it’s use, were both being done in WordPress’s init action.

The Solution

By simply using a separate WordPress action, or changing the priority of the action, I was able to ensure my custom taxonomies were registered first and were available for use by my other script.

add_action('init', 'do_my_action', 99);

The above code illustrates how to change the priority. I’ve used ’99’ to ensure it’s the very last thing that’s loaded but you can change yours accordingly.