Vous êtes sur la page 1sur 8

Hiring? Toptal handpicks top WordPress engineers to suit your needs.

Start hiring
Login

Top 3%
Why
Clients
Partners
Community
Blog
About Us
Start hiring
Apply as a Developer
Login
Questions?
Contact Us

Search Topics
Hire a developer

How to Create Exclusive Custom Taxonomies in WordPress


View all articles

by Rodrigo Donini - Freelance Software Engineer @ Toptal

#Taxonomies #WordPress

31shares

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.
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: category, tag, link 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_terms, edit_terms, manage_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.

Lets 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.

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:
Like what you're reading?
Get the latest updates first.
Enter your email address...
Get Exclusive Updates
No spam. Just great engineering posts.
Like what you're reading?
Get the latest updates first.
Thank you for subscribing!
Check your inbox to confirm subscription. You'll start receiving posts after you confirm.

109shares

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
<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() functionwe 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; well 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:

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_post hook:

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 thats 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!

Understanding the Basics


What is a WordPress taxonomy?

In WordPress, a taxonomy is a way of grouping posts and pages under different terms with common characteristics.

About the author


View full profile
Hire the Author
Rodrigo Donini, Brazil
member since September 9, 2016
LESSHTML5PHPSassWordPress APITrelloWP-CLIWordPressPSD to WordPressFront-end+2 more
Rodrigo is a focused developer who produces digital projects for agencies around the world. He has 17 years of experience using various technologies and methodologies in most web and
mobile projects. He has a strong knowledge of the WordPress world and is very engaged with the community: building custom themes, plugins, and core customizations. He specializes in
WordPress, developing for the front-end back-end and in managing digital projects. [click to continue...]
Hiring? Meet the Top 10 Freelance WordPress Developers for Hire in December 2017
3 Comments Toptal
1 Login

Sort by Best
Recommend Share

Join the discussion

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

Avag Sargsyan a month ago


Nice article, thanks!
Reply Share

Chris Marshall a month ago


Although every site is different, you may want to noindex Tags. Indexing Categories is fine especially when it comes to ecommerce sites. Keep in mind that Categories are
hierarchical and Tags are not hierarchical.
Reply Share

Tutomena.com a month ago


Thank you!
Good tutorial.
Reply Share

Subscribe d Add Disqus to your siteAdd DisqusAdd Privacy

comments powered by Disqus


Subscribe
The #1 Blog for Engineers
Get the latest content first.
Enter your email address...
Get Exclusive Updates
No spam. Just great engineering posts.
The #1 Blog for Engineers
Get the latest content first.
Thank you for subscribing!
Check your inbox to confirm subscription. You'll start receiving posts after you confirm.

109shares
Trending articles
Fastlane: iOS Automation on Cruise Control2 days agoMagento 2: Revision or Revolution?3 days agoGetting Started with the Elm Programming Language9 days agoGraphQL vs. REST -
A GraphQL Tutorial12 days agoTips to Attract, Manage, and Retain Software Developers16 days agoGetting Started with TensorFlow: A Machine Learning Tutorial17 days agoQuick
Wins in the Enterprise With Salesforce AppExchange24 days agoFrom Solving Equations to Deep Learning: A TensorFlow Python Tutorial25 days ago
Relevant Technologies

PHP
WordPress

About the author

Rodrigo Donini
Wordpress Developer
Rodrigo is a focused developer who produces digital projects for agencies around the world. He has 17 years of experience using various technologies and methodologies in most web and
mobile projects. He has a strong knowledge of the WordPress world and is very engaged with the community: building custom themes, plugins, and core customizations. He specializes in
WordPress, developing for the front-end back-end and in managing digital projects.

Hire the Author


Toptal connects the top 3% of freelance talent all over the world.

Toptal Developers
Android Developers
AngularJS Developers
Back-End Developers
C++ Developers
Data Scientists
DevOps Engineers
Ember.js Developers
Freelance Developers
Front-End Developers
Full Stack Developers
HTML5 Developers
iOS Developers
Java Developers
JavaScript Developers
Machine Learning Engineers
Magento Developers
Mobile App Developers
.NET Developers
Node.js Developers
PHP Developers
Python Developers
React.js Developers
Ruby Developers
Ruby on Rails Developers
Salesforce Developers
Scala Developers
Software Developers
Unity or Unity3D Developers
Web Developers
WordPress Developers

See more freelance developers


Learn how enterprises benefit from Toptal experts.

Join the Toptal community.


Hire a developer
or
Apply as a Developer

Highest In-Demand Talent


iOS Developer
Front-End Developer
UX Designer
UI Designer
Financial Modeling Consultants
Interim CFOs

About

Top 3%
Clients
Freelance Developers
Freelance Designers
Freelance Finance Experts
About Us

Contact
Contact Us
Press Center
Careers
FAQ

Social

Facebook
Twitter
Google+
LinkedIn

Toptal

Hire the top 3% of freelance talent

Copyright 2010 - 2017 Toptal, LLC

Privacy Policy
Website Terms

Home Blog How to Create Exclusive Custom Taxonomies in WordPress


Hiring? Toptal handpicks top WordPress engineers to suit your needs.

Start hiring
Login

Vous aimerez peut-être aussi