WordPressでテンプレートパーツを作成する方法

ここでは、WordPressでテンプレートパーツを作成する方法について、説明していきます。

ファイルの作成

まずはテーマフォルダの直下に「template-parts」フォルダを作成し、その下にテンプレートパーツとなるファイルを作成します。

新たに作成したファイルにテンプレートとなるコードを記述します。

テンプレートファイルの記述例

<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>

get_template_part()

次にテンプレートパーツを使用したい部分にget_template_part()を記述します。

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

上記のように記述することで、作成したテンプレートパーツを使用することができます。

まとめ

このように、テンプレートパーツのファイルを作成し、get_template_part()で呼び出すことで、テンプレートパーツを使用することができます。