I recently built my own basic downloads manager plugin because I wanted something stupid simple. The bare functionality I needed was the title, a description, the file, and categories — So, I created a custom post type and then added a few meta boxes with the Custom Metaboxes and Fields Class.
I wrote all of the above in less than 10 minutes. The problem I then encountered was figuring out how to get the list of categories that a download was assigned to.
This is simple when just working with regular posts; Just use the get_categories()
function. However, categories within custom post types are a different beast…
Custom Post Types DO NOT Have Categories
I spent hours trying to figure out how to get the categories from a custom post type. And you know what I figured out after all of that wasted time? That custom post types do not have categories…
You see, categories are a type of taxonomy that is built-in to WordPress and used to categorize posts. When we create a “category” for a custom post type, we are actually creating a completely new taxonomy (even though we may in fact call it ‘categories’).
Take this custom taxonomy example below:
function cw_cpp_slideshow_categories() {
$field_args = array(
'labels' => array(
'name' => 'Categories', 'taxonomy general name',
'singular_name' => 'Category', 'taxonomy singular name',
'search_items' => 'Search Categories',
'all_items' => 'All Categories',
'parent_item' => 'Parent Category',
'parent_item_colon' => 'Parent Category:',
'edit_item' => 'Edit Category',
'update_item' => 'Update Category',
'add_new_item' => 'Add New Category',
'new_item_name' => 'New Category',
'menu_name' => 'Categories',
),
'hierarchical' => true
);
register_taxonomy( 'slideshow_categories', 'slideshow', $field_args );
}
add_action( 'init', 'cw_cpp_slideshow_categories', 0 );
This is some code that I use to add categories to a slideshow custom post type. Look specifically at the line where I call register_taxonomy() . Notice how I define the taxonomy as slideshow_categories , then assign it to post type slideshow , then I pass in various arguments, such as labels, in the 3rd parameter.
So, while I created a taxonomy that looks and functions almost exactly like categories does with posts… I actually created a new taxonomy named slideshow_categories .
Confusing? Yea, a bit…

Well, here’s a little bit more confusion. You know what you usually call categories? Those are actually named terms in other taxonomies…
So, How Do I Get Categories for Custom Post Types?
The answer is pretty simple — just use get_terms(). The only parameter you need to pass in to get_terms() is a taxonomy name, slideshow_categories from the example above.
But, if you need to do some special ordering, excludes, etc… You can also pass an array of arguments as the second parameter. Check out the codex for get_terms().
Questions or Comments?
If this helped you or if you just find it funny how long it took me to figure this out… leave comment below!
Leave a Reply