Archived topic
Add Post Tags to Body Class
2 replies · Started by Sam on May 22, 2017
Seen this successfully done with categories, but for some reason I can't make it work with post tags.
Usage case: Want all posts with tag "course" to have a specific layout and styling applied. Best way I can think of to target them is to target body.tag-XXXX in CSS.
This is the code I've tried, which adds the tags to the article (same happens with generate_main_class), but not to the body.
function tags_to_body_class( $classes ) {
global $post;
$posttags = get_the_tags( $post->ID );
if ( $posttags ){
foreach( $posttags as $tag )
$tags[] = $tag->slug;
return $tags;
}
add_filter('body_class', 'tags_to_body_class');
}
Needed to move add_filter line *OUTSIDE* of the function brackets, duh. Couldn't find a way to delete this post. Hopefully this helps someone else.
Glad you found a solution! :)