Why a Custom Taxonomy Might Not Be Returned in WordPress

July 14th, 2014 - Posted by Steve Marks to PHP, Software, Web Development.

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.

I added an action in my script like so that would assign the post:

$return = wp_set_object_terms( $post_id, array(1, 2, 5), 'my-custom-taxonomy' );


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:

$taxonomies = get_taxonomies( '', 'names' ); 
foreach ($taxonomies as $taxonomy ) {
  echo '

'. $taxonomy. '

'; }

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.

This entry was posted on Monday, July 14th, 2014 at 10:48 am by +Steve Marks and is filed under PHP, Software, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (1)
  1. Sergey says:

    Thanks a lot! It really helps me, when i set high priority