如何在自定义帖子类型循环中将帖子标签添加为类?

时间:2019-05-13 20:08:43

标签: wordpress loops tags custom-post-type

我有一个自定义循环,用于自定义帖子类型,效果一直很好,但是我想基于每个帖子的标记标签向div包装器(.room_entry)添加一个类。这是我到目前为止所得到的:

我正在尝试添加“。get_the_tags()。”直接上课,但似乎无效。该类输出“数组”

//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;
}

1 个答案:

答案 0 :(得分:1)

    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;