Friday, January 17, 2014

How To Create Custom Taxonomies In WordPress

_get_object_terms() function.

Create a Taxonomy Tag Cloud

A tag cloud provides a great way for users to browse content. The wp_tag_cloud() function makes creating a tag cloud with a custom taxonomy easy.
WordPress taxonomy term cloud example
Let’s use it to display a tag cloud of our location terms:
// Locations tag cloud
<?php
$locations_cloud = wp_tag_cloud( array(
 'taxonomy' => 'location',
 'echo' => 0
) );

// Make sure there are terms with articles
if ( $locations_cloud ): ?>
<h2>News by Location</h2>
<div class="locations-cloud">
 <?php echo $locations_cloud; ?>
</div>
<?php endif; ?>

Get All Terms in a Taxonomy

You will often need to work with a full list of terms in a taxonomy, and the get_terms() function can be quite handy for this. Let’s use it to show off the number of locations to which we’re providing news:
<?php
// Get a list of all terms in a taxonomy
$terms = get_terms( "location", array(
 'hide_empty' => 0,
) );
$locations = array();
if ( count($terms) > 0 ):
 foreach ( $terms as $term )
  $locations[] = $term->name;

 $locations_str = implode(', ', $locations);
?>
<h2>Nationwide Coverage</h2>
<p>We cover stories around the country in places like <?php echo $locations_str; ?> and more. If we're not the best source for the latest news in your area, let us know!</p>
<?php endif; ?>
This will output the following HTML:
<h2>Nationwide Coverage</h2>
<p>We cover stories around the country in places like Boston, London, New York, San Francisco and more. If we're not the best source for the latest news in your area, let us know!</p>
This simple approach may not show it, but the get_terms() function is incredibly powerful. It allows you to get terms from multiple taxonomies at once by passing an array that contains the names of your taxonomies as the first parameter.

Working With WP_Query and tax_query

The WP_Query class enables you to create a custom loop. WordPress 3.1 introduced a new parameter for the class called tax_query, which allows you to display content from a taxonomy in many unique ways.
Let’s use it to create a list of the most recent news posts in Boston.
<?php
/**
 * Display a list of the most recent news in Boston
 *
 * @class WP_Query http://codex.wordpress.org/Class_Reference/WP_Query
 */
$locations_query = new WP_Query( array(
 'post_type' => 'post',
 'posts_per_page' => 10,
 'tax_query' => array(
  array(
   'taxonomy' => 'location',
   'field' => 'slug',
   'terms' => 'boston'
  )
 )
) );
// Display the custom loop
if ( $locations_query->have_posts() ): ?>
<h2>Latest News in Boston</h2>
<ul class="postlist">
 <?php while ( $locations_query->have_posts() ) : $locations_query->the_post(); ?>
 <li><span class="date"><?php the_time(get_option('date_format')); ?></span><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></li>
 <?php endwhile; wp_reset_postdata(); ?>
</ul><!--// end .postlist -->
<?php endif; ?>
We could easily make this set-up dynamic by using the get_term_by() or get_terms() functions that we discussed earlier.

Attaching Additional Data to a Taxonomy

Each taxonomy term has specific data associated with it. Out of the box, WordPress allows you to store the following information for each taxonomy term:
  • Name,
  • Slug,
  • Parent,
  • Description.
But what if you need to store more information, such as an image for the taxonomy term or a title and description for search engines, or maybe even attach the term to a particular author the way a traditional news column does? Since WordPress 2.9, developers have been able to attach additional meta data to posts, pages, custom post types, comments and users using the add_metadata(), update_metadata() and get_metadata() functions. But this does not include taxonomies such as tags and categories.
With the help of the Taxonomy Metadata plugin, we can attach meta data to taxonomy terms for both built-in and custom taxonomies. This enables us to create additional taxonomy fields that will be stored in a new taxonomymeta database table.
Note to Multisite developers: I’ve encountered issues using the Taxonomy Metadata plugin on a WordPress Multisite installation. Activating the plugin network-wide results in data not being saved. Instead, activate the plugin individually for each website, and it will work properly.
(Knowing the story behind this technique and what it might mean for future WordPress upgrades is important. Currently, there is a debate on the WordPress Trac project about the best method for this. The method I’ll show you is one suggested by various WordPress core developers. But I strongly urge you to review the Trac project and the Codex. A standard approach could very well be built into WordPress in the future, which would therefore be more practical than what I am about to show you.)
The prerequisite to all of the examples below is to install and activate the Taxonomy Metadata plugin.

Add Search Engine Title and Description Fields to Categories and Tags

We will use action hooks to gracefully attach additional fields to our taxonomies without editing WordPress’ core. If you’ve made it this far, then you probably have a working knowledge of WordPress filters and actions. To learn about working with hooks, I highly suggest Daniel Pataki’s article on the subject.
WordPress taxonomy meta data: Search engine title and description fields added to categories and tags
Let’s start by adding a text input and a textarea field to the “Add New” and “Edit” term pages on the WordPress admin screen. We do this by placing the following functions in our theme or plugin.
The taxonomy_metadata_add() function attaches the fields to the /wp-admin/edit-tags.php?taxonomy=%taxonomy% page.
The %taxonomy% item in the URL above will change depending on the term you are editing.
/**
 * Add additional fields to the taxonomy add view
 * e.g. /wp-admin/edit-tags.php?taxonomy=category
 */
function taxonomy_metadata_add( $tag ) {
 // Only allow users with capability to publish content
 if ( current_user_can( 'publish_posts' ) ): ?>
 <div class="form-field">
  <label for="meta_title"><?php _e('Search Engine Title'); ?></label>
  <input name="meta_title" id="meta_title" type="text" value="" size="40" />
  <p class="description"><?php _e('Title display in search engines is limited to 70 chars'); ?></p>
 </div>

 <div class="form-field">
  <label for="meta_description"><?php _e('Search Engine Description'); ?></label>
  <textarea name="meta_description" id="meta_description" rows="5" cols="40"></textarea>
  <p class="description"><?php _e('The meta description will be limited to 156 chars by search engines.'); ?></p>
 </div>
 <?php endif;
}
The taxonomy_metadata_edit() function attaches the fields to the /wp-admin/edit-tags.php?action=edit&taxonomy=%taxonomy%&tag_ID=%id%&post_type=%post_type% page.
The %taxonomy%, %id% and %post_type% items in the URL above will change depending on the term you are editing.
We’ll use the get_metadata function here to display any saved data that exists in the form.
/**
 * Add additional fields to the taxonomy edit view
 * e.g. /wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=27&post_type=post
 */
function taxonomy_metadata_edit( $tag ) {
 // Only allow users with capability to publish content
 if ( current_user_can( 'publish_posts' ) ): ?>
 <tr class="form-field">
  <th scope="row" valign="top">
   <label for="meta_title"><?php _e('Search Engine Title'); ?></label>
  </th>
  <td>
   <input name="meta_title" id="meta_title" type="text" value="<?php echo get_term_meta($tag->term_id, 'meta_title', true); ?>" size="40" />
   <p class="description"><?php _e('Title display in search engines is limited to 70 chars'); ?></p>
  </td>
 </tr>

 <tr class="form-field">
  <th scope="row" valign="top">
   <label for="meta_description"><?php _e('Search Engine Description'); ?></label>
  </th>
  <td>
   <textarea name="meta_description" id="meta_description" rows="5" cols="40"><?php echo get_term_meta($tag->term_id, 'meta_description', true); ?></textarea>
   <p class="description"><?php _e('Title display in search engines is limited to 70 chars'); ?></p>
  </td>
 </tr>
 <?php endif;
}
These two functions control the output of the form fields. I’ve used HTML that follows WordPress’ UI patterns and styles guidelines for the admin area.
Saving the form’s data to the taxonomymeta database table
Now that we’ve added the form fields, we’ll need to process and save the data with the update_term_meta function that is provided by the plugin.
/**
 * Save taxonomy metadata
 *
 * Currently the Taxonomy Metadata plugin is needed to add a few features to the WordPress core
 * that allow us to store this information into a new database table
 *
 * http://wordpress.org/extend/plugins/taxonomy-metadata/
 */
function save_taxonomy_metadata( $term_id ) {
 if ( isset($_POST['meta_title']) )
  update_term_meta( $term_id, 'meta_title', esc_attr($_POST['meta_title']) );

 if ( isset($_POST['meta_description']) )
  update_term_meta( $term_id, 'meta_description', esc_attr($_POST['meta_description']) );
}
Add the new taxonomy fields
Now that everything is in place, we’ll use action hooks to load our new functions in all the right places. By hooking the following function into the admin_init action, we ensure that it runs only on the admin side of WordPress. First, we need to make sure that the functions added by the Taxonomy Metadata plugin are available. Next, we use the get_taxonomies() function to attach the new taxonomy fields to every public taxonomy, including the built-in tags and categories.
/**
 * Add additional taxonomy fields to all public taxonomies
 */
function taxonomy_metadata_init() {
 // Require the Taxonomy Metadata plugin
 if( !function_exists('update_term_meta') || !function_exists('get_term_meta') ) return false;

 // Get a list of all public custom taxonomies
 $taxonomies = get_taxonomies( array(
  'public'   => true,
  '_builtin' => true
 ), 'names', 'and');

 // Attach additional fields onto all custom, public taxonomies
 if ( $taxonomies ) {
  foreach ( $taxonomies  as $taxonomy ) {
   // Add fields to "add" and "edit" term pages
   add_action("{$taxonomy}_add_form_fields", 'taxonomy_metadata_add', 10, 1);
   add_action("{$taxonomy}_edit_form_fields", 'taxonomy_metadata_edit', 10, 1);
   // Process and save the data
   add_action("created_{$taxonomy}", 'save_taxonomy_metadata', 10, 1);
   add_action("edited_{$taxonomy}", 'save_taxonomy_metadata', 10, 1);
  }
 }
}
add_action('admin_init', 'taxonomy_metadata_init');
That’s it. We’re done!
You should now see two additional fields in your tags, categories and public custom taxonomies. As mentioned at the beginning of this section, the technique can be used to handle many different scenarios. This basic framework for storing and retrieving information associated with a taxonomy should have you well on your way to mastering the management of taxonomy content.

In Conclusion

I hope you better understand how to organize WordPress content with the help of taxonomies. Whether hierarchal or multifaceted, a well-implemented taxonomy will simplify the way content is organized and displayed on a website. WordPress has all of the tools you need to create custom taxonomies and to group your content in new and exciting ways. How you use them is up to you!