2017-03-17 3 views
0

最新の3つの投稿を取得し、各投稿のタイトルとカテゴリを表示するループを作成します。私が持っているループは、現在、各投稿の正しい値を取得していますが、foreachループはすべての前回の投稿の値を追加していますので、3番目の投稿では、以前の投稿のカテゴリ3番目の投稿。Wordpressのforeachループが多すぎるカテゴリを表示しています - 現在の投稿のカテゴリがほしいだけです

Post1をAとB、Post2をCとDに分類すると、Post2はABCDとして分類されていることを示しています。誰かが私が間違っているのを見ることができますか?前もって感謝します。

<section class="blog-index"> 
     <?php 
      $args = array('showposts' => 3); 
      $recent = new WP_Query($args); 

      if($recent->have_posts()): 
       echo '<div class="blog-index-list">'; 

       while ($recent->have_posts()) : $recent->the_post(); 
       $categories = get_the_category(); 
         foreach($categories as $category) { 
          $cat .= $category->name;        
         }; 


        echo '<article>      
         <h2><a href="'.get_the_permalink().'">' .get_the_title(). '</a></h2> 
         <p class="post-cats"> ' . $cat . '</p> 
         <img src="'.get_the_post_thumbnail().'' . 
         '<div class="blog-index-button et_pb_button_module_wrapper et_pb_module et_pb_button_alignment_center"> 
          <a class="et_pb_button et_pb_button_3 et_pb_module et_pb_bg_layout_light" href="' . get_the_permalink() . '">READ POST</a> 
         </div>     
         </article>'; 
       endwhile; 
       echo '</div>'; 
      endif; 
      wp_reset_query(); 
     ?>  
    </section> 

答えて

1

$ cat変数をクリアしていないようです。 。=を使用して$ catにデータを追加する場合、foreachの各呼び出しの間に$ cat = ""を設定する必要があります。

+0

それはそれでした!ありがとう@幸せ – AFarkas

関連する問題