How to Create Exclusive Custom Taxonomies in WordPress

Please follow and like us:
RSS
Facebook
Facebook
Twitter

WordPress, one of the most powerful open source blogging and content management systems, is being used to power a major chunk of the interwebs.

Unlike many other CMSes, WordPress is loved by many for its flexibility and customizability. Taxonomies, one of the core features of WordPress, allows you to organize content just the way you need to. Although it comes built-in with a few default taxonomies, WordPress lets you add as many custom taxonomies as you please.

However, getting taxonomies to behave exactly the way you want them to may require you to fiddle with some undocumented approaches.

Graphic representation of the various WordPress taxonomy options

In this article, you will learn how you can define exclusive custom taxonomies in WordPress that behave much more like categories than tags, allowing you to categorize your posts much more strictly than you can out of the box.

What Is a Taxonomy?

According to the WordPress codex:

A taxonomy is a way to group things together.

For example, a bunch of different types of fruits can be grouped together according to various characteristics and then those groups can be assigned names.

In WordPress, taxonomies are used to group posts, pages, and even custom post types under different groups.

The names for the different groupings in a taxonomy are called terms. Take fruits, for example, and how they can be grouped based on their colors. In this case, the names of different colors would be the terms.

By default, WordPress comes built in with four taxonomies: categorytaglink category, and post format. You can learn more about these default taxonomies here.

Among these built-in taxonomies, categories and tags are very similar but have one important difference: Categories are exclusive taxonomies (i.e., for each post, you may select at most one category) whereas each post can be assigned multiple tags.

Moreover, categories are usually predefined, while tags may be defined as you go.

Defining Custom Taxonomies

You can define a custom taxonomy using the register_taxonomy() function. You can learn more about the function here.

To see how this function works, let us define a custom taxonomy for posts with photos of scenery.

function view_init() {
	register_taxonomy(
		'view',
		'post',
		array(
			'label' => __( 'View' ),
			'capabilities' => array(
				'assign_terms' => 'edit_guides',
				'edit_terms' => 'publish_guides'
			)
		)
	);
}
add_action( 'init', 'view_init' );

In the above snippet, we are defining a new taxonomy for posts called view.

You can think of this taxonomy being used to categorize photos based on the kind or nature of views that are present in the photos (e.g., mountain, lake, or forest).

As always, posts that belong to specific terms of this category will appear under /view/{view_name}.

The capabilities line in the snippet above is optional. Without it, WordPress will default capabilities to the same users as posts. As shown above, this will allow any user with the custom “edit_guides” capability to assign the taxonomy to a post and any user with the custom “publish_guides” capability to create new taxonomy items.

According to the official documentation, there are four capabilities that may be defined:

Taxonomy capabilities include assign_termsedit_termsmanage_terms (displays the taxonomy in the admin navigation) and delete_terms.

How Taxonomies Are Used

Within your code, you can use the wp_set_object_terms() function to add terms to objects using the taxonomy. You can list existing terms using the the_terms() function. Furthermore, you can use the wp_tag_cloud() function to generate a cloud of terms for your custom taxonomy. You can learn more about these functions here.

On the UI side, WordPress creates a new meta box on posts for every taxonomy. The meta box is similar to the Tags meta box which lets you link one or more terms to your post. This is what WordPress does by default, and this is what we can change by making a taxonomy exclusive: Make the custom taxonomy behave like the category taxonomy.

Forcing Exclusiveness on Taxonomies

When we create a custom taxonomy with the register_taxonomy() method, WordPress adds a meta box with multiple item selection to the post editing page:

Using this meta box, a user can choose any number of existing (already used) terms and also can add new terms using the text box.

To create a category-like taxonomy, where each post belongs to at most one category from a set of predefined categories, you can do so by tweaking WordPress a little:

  • Hide the default meta box created by WordPress.
  • Create a custom meta box on post editing page which will provide controls for single item selection.
  • Save the taxonomy value when the post is saved.

Let’s take a look at each of the steps.

Hide the Default Meta Box Created by WordPress

For this, we need to set show_in_quick_edit and meta_box_cb options to false when calling register_taxonomy.

Screenshot of a custom taxonomy meta box where you can add items to the set of available terms

The first option hides the taxonomy in the quick/bulk edit panel and the second option hides it in the post edit page:

register_taxonomy( 'custom_taxonomy', 'post', array(
	'labels' => array(
		'name' => 'Custom Exclusive Taxonomy'
	),
	'show_in_quick_edit' => false,
	'meta_box_cb' => false
));

When the default meta box is hidden, items can be added to the set of available terms of the taxonomy via the taxonomy management page:

Screenshot of a meta box named Custom Exclusive Taxonomy with several radio buttons

Like what you’re reading?
Get the latest updates first.
No spam. Just great engineering posts.

Create a Custom Meta Box on the Post Editing Page

To create a custom meta box, we can use the add_meta_boxes WordPress hook. You can learn more about the hook here.

add_action('add_meta_boxes', 'add_custom_meta_box');
function add_custom_meta_box(){
	add_meta_box( 'taxonomy_box', __('Custom Exclusive Taxonomy'), 'fill_custom_meta_box_content', 'post' ,'side');
}

We call the add_meta_box method with the following arguments:

  • taxonomy_box – The ID of the meta box
  • __('Custom Exclusive Taxonomy') – The title of the meta box
  • fill_custom_meta_box_content – A function that is used to fill the contents of the meta box
  • post – This indicates that the meta box should appear on the post editing page.
  • side – This indicates the place where the meta box should be inserted.

Notice how we specified taxonomy_box as the ID. However, it is the function in the third parameter that will let us define what will go into the box.

We will now implement the fill_custom_meta_box_content function:

<?php
function fill_custom_meta_box_content( $post ) {
	$terms = get_terms( array(
		'taxonomy' => 'custom_taxonomy',
		'hide_empty' => false // Retrieve all terms
	));

	// We assume that there is a single category
	$currentTaxonomyValue = get_the_terms($post->ID, 'custom_taxonomy')[0];
?>
	<p>Choose taxonomy value</p>
	<p>
		<?php foreach($terms as $term): ?>
			<input type="radio" name="custom_taxonomy" id="taxonomy_term_<?php echo $term->term_id;?>" value="<?php echo $term->term_id;?>"<?php if($term->term_id==$currentTaxonomyValue->term_id) echo "checked"; ?>>
			<label for="taxonomy_term_<?php echo $term->term_id;?>"><?php echo $term->name; ?></label>
			</input><br/>
		<?php endforeach; ?>
	</p>
<?php
}

Here, we are first retrieving all of the terms (i.e., existing values) of the taxonomy. We will use these to show a list of radio button controls.

Next, we retrieve the currently selected taxonomy term using get_the_terms() function—we need it to make the respective radio button selected.

Notice that this function returns an array. This is because, by default, the post can have any number of terms associated with it. By our assumption, the post has at most one term, so we access the first array element. (It is ok if the array is empty; we’ll get null as the current value and no radio button will be selected.)

The HTML emitting code uses custom_taxonomy as the name of radio buttons and corresponding term IDs as their values; radio button ID attributes are just used for connecting to label tags. As a result, we get the following custom meta box:

Screenshot of Custom Exclusive Taxonomy's "add new tag" feature now available on the WordPress dashboard sidebar

Save the taxonomy Value When the Post Is Saved

Finally, we need to persist the taxonomy value when the post is saved. For this, we can use the save_posthook:

add_action('save_post', 'save_custom_taxonomy');

function save_custom_taxonomy($post_id){
	if ( isset( $_REQUEST['custom_taxonomy'] ) ) 
		wp_set_object_terms($post_id, (int)sanitize_text_field( $_POST['custom_taxonomy'] ), 'custom_taxonomy');
}

And that’s it! We are done.

You now know how to define a custom taxonomy that will behave like the built-in category taxonomy.

Note: WordPress has accepted a feature request to make it easier to toggle exclusivity for custom taxonomies. However, the ticket has not seen much activity for a while.

Wrap Up

Taxonomies are a very powerful and useful feature in WordPress. Out of the box, they lack the ability to make strict categorization of posts, but as with nearly anything in WordPress, taxonomies and related functionality are extremely customizable. This allows us to add this often necessary ability in a few steps.

The approach introduced here can also be used to create even more customized UI on post editing pages for the taxonomy term selection.

I hope you have found this quick tutorial on defining exclusive custom taxonomies useful!

in collaboration with Toptal and post by Narek Malkhasyan

Please follow and like us:
RSS
Facebook
Facebook
Twitter