Skip to content

Instantly share code, notes, and snippets.

@cdils
Last active December 24, 2015 21:59
Show Gist options
  • Select an option

  • Save cdils/6869728 to your computer and use it in GitHub Desktop.

Select an option

Save cdils/6869728 to your computer and use it in GitHub Desktop.
Use within the loop (on a single post) to grab all taxonomy terms for post. Take each term and add it as a custom body class.
//* Add taxonomy term as body class to the header
add_filter( 'body_class', 'cd_body_class' );
function cd_body_class( $classes ) {
// Create array of terms within taxonomy named "group"
$terms = get_the_terms( $post->ID , 'group' );
// If there are no terms, bail
if ( $terms == null )
$return;
// Loop through terms array and assign as body class
foreach( $terms as $term ) {
$classes[] = $term->slug;
}
return $classes;
}
@bradyvercher
Copy link
Copy Markdown

No problem.

! $terms isn't the same as an empty() check (unless the value really is null), but if you look at the possible return values for get_the_terms(), they are array|bool|WP_Error. Looking at the function, it does its own check for an empty value and returns false, so you'll never receive an empty value. The ! $terms is just verifying that $terms isn't false.

Typically API functions should try to standardize their output and may do some error checking (and caching in this case) of their own to help keep your code a bit cleaner without having to check for more than a couple of response formats.

If figured as much regarding that return, who doesn't like extra dollars? Rather than just the return in a filter like this, you'd probably want to return the original $classes parameter so the existing body classes don't get blanked out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment