STEP5:カスタムテンプレート
STEP3で学んだテンプレート階層に基づき、用途ごとに専用のテンプレートファイルを作成していきます。これによりテーマの完成度が大きく高まります。
single.php(個別投稿ページ)
<?php get_header(); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article <?php post_class(); ?>>
<h1><?php the_title(); ?></h1>
<?php if (has_post_thumbnail()) the_post_thumbnail(); ?>
<div><?php the_content(); ?></div>
</article>
<?php endwhile; endif; ?>
<?php get_footer(); ?>
page.php(固定ページ)
固定ページ用のテンプレートです。single.phpと似ていますが、コメント欄や投稿日等、時系列コンテンツ特有の要素を省略するのが一般的です。
archive.php(アーカイブ一覧)
<?php get_header(); ?>
<h1><?php the_archive_title(); ?></h1>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php endwhile; endif; ?>
<?php the_posts_pagination(); ?>
<?php get_footer(); ?>
共通パーツの分割(get_template_part)
投稿一覧の各記事表示など、複数のテンプレートで繰り返し使う部分は、get_template_part()で別ファイルに切り出すと保守性が高まります。
<?php get_template_part('template-parts/content', get_post_type()); ?>