You can follow similar approach with get_the_terms
.
Here is the function.
function add_taxonomy_to_single( $classes ) {
if ( is_single() ) {
global $post;
$my_terms = get_the_terms( $post->ID, 'custom-taxonomy' );
if ( $my_terms && ! is_wp_error( $my_terms ) ) {
foreach ($my_terms as $term) {
$classes[] = $term->slug;
}
}
return $classes;
}
}
add_filter( 'body_class', 'add_taxonomy_to_single' );
Don’t forget to change the name of your custom taxonomy in above code. I used custom-taxonomy
for example.
EDIT 1:
To add first taxonomy name in body class here it the updated code.
function add_taxonomy_to_single( $classes ) {
if ( is_single() ) {
global $post;
$my_terms = get_the_terms( $post->ID, 'custom-taxonomy' );
if ( $my_terms && ! is_wp_error( $my_terms ) ) {
$classes[] = $my_terms[0]->slug;
}
return $classes;
}
}
add_filter( 'body_class', 'add_taxonomy_to_single' );