WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to add post_tags to body_class() (2 posts)

  1. BugiuAlex
    Member
    Posted 2 years ago #

    Hello and thx for taking the time to look over this.

    I am trying to add a body class for a single post. The body class i want it to be the post tag(s).

    I tried using the function for category, but it didn't work. Here is the code:

    // add category nicenames in body and post class
    function category_id_class($classes) {
    	global $post;
    	foreach((get_the_tags($post->ID)) as $tag)
    		$classes[] = $tag->name;
    	return $classes;
    }
    add_filter('post_class', 'category_id_class');
    add_filter('body_class', 'category_id_class');

    Been at it for a few good hours, didn't find anything specific on google. And i am not very good with php.

    Thank you in advance

  2. BugiuAlex
    Member
    Posted 2 years ago #

    Went back to a function i tried a night before when i think i was a bit tired and i must have slipped an error.
    here it is:

    // add tags in body
        function tags_id_class($classes) {
              global $post;
              $tag_names = wp_get_post_tags ($post->ID, array('fields' => 'names' ) );
              foreach ($tag_names as $tag)
                 $classes[] = $tag;
              return $classes;
        }
        add_filter('body_class', 'tags_id_class');

    Now when calling <body <php? body_class(); ?>> it is outputting the tag name as well.
    Hope it helps someone else.

Topic Closed

This topic has been closed to new replies.

About this Topic