Using Taxonomies

Taxonomies allow you to organize content in different ways. I'll walk you through creating and implementing custom taxonomies, as well as show you how I used taxonomies for my personal portfolio.

A taxonomy is a way to organize content. You've probably used two taxonomies before: categories and tags. WordPress allows you to create as many as you'd like to organize your content in whatever ways make sense to you.

I often use taxonomies when I'm creating custom post types . Categories and tags make sense for posts, but when you make a new content type you might also need to create new ways of organizing that content.

My Code Snippets post type uses a "Code Tag" taxonomy for organizing content. You can see all code snippets relating to my Display Posts Shortcode plugin here .

Creating Custom Taxonomies

In your core functionality plugin , you can create a new taxonomy using the register_taxonomy() function. Here's an example of registering a "color" taxonomy for posts:

https://gist.github.com/billerickson/5a445e78b06081fc80918c957a589018

Labels

The labels parameter lets you customize all the labels used throughout the WordPress backend. It’s usually as simple as find/replacing the plural and singular forms of the taxonomy, but you may want to tweak some of the other labels more extensively.

Hierarchical

If 'hierarchical' => true, it will have a hierarchical structure like Categories. If 'hierarchical' => false, it will be non-hierarchical like Tags.

Rewrite

The rewrite parameter lets you enable and customize the URL rewriting for this content type.

Show Admin Column

If 'show_admin_column' => true, the taxonomy will be included on the Edit Posts screen.

Metabox Callback

If 'meta_box_cb' => false, no metabox appears for managing the taxonomy on the Edit Post screen. This is useful if you create a custom metabox that includes taxonomy management.

Displaying Custom Taxonomies

Once you've created your taxonomy and added some terms, you'll want to display the terms attached to a post. You can use the function the_terms() .

the_terms( get_the_ID(), 'color', 'colors: ', ', ' );

The first argument is for the post ID, the second for the taxonomy name, the third for what's displayed before the listing, the fourth shows the separator to use if there's multiple terms (I'm separating with commas), and the last argument is for what's displayed after the listing.

Sorting by Taxonomy

You can customize the main query or create custom queries that leverage your taxonomies using tax_query.

For instance, to get the 10 most recent posts with the color "blue":

https://gist.github.com/billerickson/1a06ae3f018baaf039729d13e97c00b1

No comments yet