Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    Hook the filter ‘body_class’. This filter fires anytime a body tag is output for any front end page. It passes an array where each element value is a class name. If is_single() is true, use the global $wp_query to get the post ID with $wp_query->get_queried_object_id() with which you can get an array of tags. Extract the tag name and add it to the class name array. Then return the entire array.

    Thread Starter jeffersonpowers

    (@jeffersonpowers)

    Thanks very much for your reply, but I’m afraid I’m not really a coder, so I didn’t really follow any of that. Can you point me to an example of code that can be added to my theme functions that will do this?

    http://codex.wordpress.org/Function_Reference/body_class#Add_Classes_By_Filters
    http://codex.wordpress.org/Function_Reference/get_the_tags

    example (untested):

    // Add specific CSS class by filter
    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;
    }
    Thread Starter jeffersonpowers

    (@jeffersonpowers)

    That worked perfectly, thank you so much for your help.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Add post tag name to single post body class’ is closed to new replies.