Search code examples
wordpressloopstagscustom-post-type

How to add post tags as a class on custom post type loop?


I have a custom loop for a custom post type that has been working great, but I would like to add a class to the div wrappers (.room_entry) based on tagged tags for each post. This is what I got so far:

I'm trying to add ". get_the_tags() ." directly to the class, but it doesn't seem to work. The class outputs 'Array'

//Display Rooms Feed
function rooms_function() {
 global $post;

 $html = "";

 $my_query = new WP_Query( array(
    'post_type' => 'room',
    'posts_per_page' => -1 ,
    'orderby'          => 'menu_order',
    'order'            => 'ASC',
));


 if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();

    $html .= "<div class='room_entry ". get_the_tags() ." '>";
    $html .= "<div class='room_image'>" .get_the_post_thumbnail() . "</div>";
    $html .= "<h4 class='room_title'>" . get_the_title() . " </h4>";
    $html .= "<p class='room_description'>" .get_field('description') . "</p>";
    $html .= "<a class='room_view' href=' ".get_permalink() ." '>View Details</a>";
    $html .= "<a class='room_book et_pb_button' target='_blank' href=' ".get_field('book_now') ." '>Book Now</a>";
    $html .= "</div>";
   endwhile;
 wp_reset_postdata();

endif;

return $html;
}

Solution

  •     if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();
    
    //Add tags as class for single or multiple tags.
        $post_tags = get_the_tags(); 
        $class = array();
        for($i=0; $i < count($post_tags); $i++){
            $class[] = $post_tags[$i]->name; 
        } 
        $classfinal = implode(' ',$class);
    
            $html .= "<div class='room_entry ". $classfinal ." '>";
            $html .= "<div class='room_image'>" .get_the_post_thumbnail() . "</div>";
            $html .= "<h4 class='room_title'>" . get_the_title() . " </h4>";
            $html .= "<p class='room_description'>" .get_field('description') . "</p>";
            $html .= "<a class='room_view' href=' ".get_permalink() ." '>View Details</a>";
            $html .= "<a class='room_book et_pb_button' target='_blank' href=' ".get_field('book_now') ." '>Book Now</a>";
            $html .= "</div>";
           endwhile;
         wp_reset_postdata();
    
        endif;