【问题标题】:How to add post tags as a class on custom post type loop?如何在自定义帖子类型循环中添加帖子标签作为类?
【发布时间】:2019-09-30 19:41:57
【问题描述】:

我有一个用于自定义帖子类型的自定义循环,效果很好,但我想根据每个帖子的标记标签向 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;
}

【问题讨论】:

    标签: wordpress loops tags custom-post-type


    【解决方案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;
    

    【讨论】:

    • 谢谢!那没有用。我应该在“如果条件”上方添加$post_id = get_the_ID() ; 吗?
    • 如果您的帖子有多个标签,它将以数组形式出现。要获取第一个标签名称,请使用 - $post_tags = get_the_tags();如果 ( $post_tags ) { $class= $post_tags[0]->name; }
    猜你喜欢
    • 1970-01-01
    • 2014-11-18
    • 2015-07-10
    • 1970-01-01
    • 2020-06-06
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多