WordPressのループで表示する投稿数を指定する方法

ここでは、WordPressのループで表示する投稿数を指定する方法について説明していきます。

構文

表示する投稿数を指定するには、WP_Query()の引数に「posts_per_page」を指定します。

<?php
$args = array('posts_per_page' => 表示させたい投稿数);
$query = new WP_Query($args);
if ($query->have_posts()) :
  while ($query->have_posts()) : $query->the_post();
    表示させたい内容
  endwhile;
endif;
?>

使用例

<div class="home-main-posts__cards cards">
  <?php
  $args = array('posts_per_page' => 6);
  $query = new WP_Query($args);
  if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
      get_template_part('template-parts/card');
    endwhile;
  endif;
  ?>
</div>
<!-- /.home-main-posts__cards cards -->

カードのテンプレートパーツ

<a href="<?php the_permalink(); ?>" class="cards__item card">
  <figure class="card__img-wrapper">
    <?php if (has_post_thumbnail()) : ?>
      <?php the_post_thumbnail(); ?>
    <?php else : ?>
      <?php echo wp_get_attachment_image(574); ?>
    <?php endif; ?>
  </figure>
  <div class="card__body">
    <h3 class="card__title">
      <?php the_title(); ?>
    </h3>
    <p class="card__text">
      <?php the_excerpt(); ?>
    </p>
  </div>
  <!-- /.card__body -->
</a>

出力結果

まとめ

このように、WP_Query()の引数に「posts_per_page」を指定することで、表示されるページ数を指定することができます。