0

Adding Taxonomy Terms To Post Class Automatically

The following code snippet will enable your theme to append the slug of every term of a given taxonomy that has been 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.

Source: Michael Fields on mfields


add_filter( 'post_class', 'mysite_post_class', 10, 3 );
if( !function_exists( 'mysite_post_class' ) ) {
    /**
     * Append taxonomy terms to post class.
     * @since 2010-07-10
     */
    function mysite_post_class( $classes, $class, $ID ) {
		$taxonomy = 'status';
		$terms = get_the_terms( (int) $ID, $taxonomy );
		if( !empty( $terms ) ) {
			foreach( (array) $terms as $order => $term ) {
				if( !in_array( $term->slug, $classes ) ) {
					$classes[] = $term->slug;
				}
			}
		}
        return $classes;
    }
}
Levels: Syntax: ,

  1. Avatar

    Your Name
    February 4


    CommentLuv badge