※社内専用

【Education】繰り返し処理 ~while文 (php基礎 -11-)

  • HOME
  • Education
  • 【Education】繰り返し処理 ~while文 (php基礎 -11-)

配列がなんとなくこんな感じ…というのがわかってきたところで繰り返し処理について触れていきます。

while文

これはwordpressでよくみかけます。

shortcode-news.php
while ( $the_query->have_posts() ) : $the_query->the_post();
          $html .= '<dt><p>'.get_the_time('Y n.j').'</p></dt>';
          $html .= '<dd><p><a href="'.get_the_permalink().'">'.get_the_title().'</a></p></dd>';
endwhile;
wp_reset_postdata();

(ここの繰り返し処理で扱っているものは配列ではなく、オブジェクトなのですがwordpressでよく見かける繰り返し処理はwhileが多いです。)

以下も。

archive.php
  @wpposts
    <?php $reverse = ($counter%2==0)? ' reverse': ''; $counter++; ?>
    @if( has_post_thumbnail() )
    …略
    @endif
  @wpempty
  @wpend

@wppostsはbladeの記述方法で書かれているもので
これをphpの記述に直すと

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

になります。

whileの説明は次回につづきます。