Append a posts taxonomy terms to post class.

Posted on

By Michael Fields

The following function will enable your theme to append the slug of every term of a given taxonomy that has been associated to the current post. You will most likely want to change the value of the $taxonomy variable to match a taxonomy registered for the post type you are targeting.

/**
 * Append the terms of a single taxonomy to the list of
 * classes generated by post_class().
 *
 * @since 2010-07-10
 * @alter 2012-01-06
 */
function mysite_post_class( $classes, $class, $ID ) {

	if ( is_admin() )
		return $classes;

	$taxonomy = 'bananas';

	$terms = get_the_terms( (int) $ID, $taxonomy );
	if ( is_wp_error( $terms ) || empty( $terms ) )
		return $classes;

	foreach ( (array) $terms as $term ) {
		if ( ! in_array( $term->slug, $classes ) )
			$classes[] = $term->slug;
	}

	return $classes;
}

add_filter( 'post_class', 'mysite_post_class', 10, 3 );

It is also possible to add the terms of multiple taxonomies at the same time. All you need to do is pass an array to get_terms() instead of a string. Here’s what it looks like:

/**
 * Append the terms of multiple taxonomies to the list
 * of classes generated by post_class().
 *
 * @since 2010-07-10
 * @alter 2012-01-06
 */
function mysite_post_class( $classes, $class, $ID ) {

	$taxonomies = array(
		'bananas',
		'tacos',
		'bunny-rabbits',
	);

	$terms = get_the_terms( (int) $ID, $taxonomies );

	if ( is_wp_error( $terms ) || empty( $terms ) )
		return $classes;

	foreach ( (array) $terms as $term ) {
		if ( ! in_array( $term->slug, $classes ) )
			$classes[] = $term->slug;
	}

	return $classes;
}

add_filter( 'post_class', 'mysite_post_class', 10, 3 );

6 Comments Leave a comment

  1. Ryan Stang July 20, 2010 at 1:28 am

    Great snippet! Saved my day.

  2. Alejandro Flain oflain September 16, 2010 at 5:30 pm

    its look like a great feature, can you help me where I can insert it?
    thanks

  3. Michael Fields September 16, 2010 at 11:53 pm

    Paste it into the functions.php file of your active theme.

  4. Alejandro Flain September 17, 2010 at 1:59 am

    thanks michael!

  5. Maintainer January 6, 2012 at 9:17 am

    That’s fantastic.

    How would I add multiple taxonomies though?

    I tried repeating the function with different variable names, but the class was only added to the first occurrence of the second taxonomy.

  6. Michael Fields January 6, 2012 at 10:50 am

    Hi Maintainer, I’ve posted the code that you asked for above as well as updated the code that was posted here to actually work correctly :) There were a few improvements that should have been made.

Share your thoughts

*

Subscribe without commenting

Please enter your email address and click subscribe to receive an email whenever a new comment is made about this post.

Fork me on GitHub