Ask your WordPress questions! Pay money and get answers fast! (more info)

Tags in Body_class WordPress

  • SOLVED

Greetings,

I am trying to include tags assigned to a post in the body class that appear when the post is viewed.

Example: I have a post called Thai India and I add tags called Thai Restaurant, Eastside and Eastside Dining to the post. When I view the post there is no tags under the body class.

<body id="dining" class="single single-post postid-2912 single-format-standard">

I added the following function which added my tags but they aren't standardized if that makes sense?

add_filter( 'body_class', 'single_post_tag_classes' );
function single_post_tag_classes( $classes ) {
if ( is_single() ) {
global $post;
$posttags = get_the_tags( $post->ID );
if ( $posttags ) {
foreach( $posttags as $tag ) {
$classes[] = 'tag-' . $tag->name;
}
}
}
return $classes;
}


This gives me the following:
<body id="dining" class="single single-post postid-2912 single-format-standard c-sn-sw <strong>tag-Eastside tag-Eastside Dining tag-Thai Restaurants</strong>">

What I want is:
<body id="dining" class="single single-post postid-2912 single-format-standard c-sn-sw <strong>tag-eastside tag-eastside-dining tag-thai-restaurants</strong>">

No spaces and no caps so that I can stylize each pages in my CSS.

There may be a better way to do this but this is the only code I could find that was related to TAGS.

Thanks in advance,
Tommy

Answers (1)

2016-09-09

dimadin answers:

Just change $tag->name to $tag->slug.


TWDesigns comments:

Hah! So simple and works perfect. Thank you!