パーツ化とは、共通する部分をパーツとして別ファイルに分けてしまうことです。
パーツ化すると、いろんなテンプレートで使い回すことができ、また、テンプレートパーツを修正・更新することで、すべてのページで修正・更新されることになるので、メンテナンスや管理がとても楽になります。
ほとんどのWordPressテーマでみられる「header.php」「footer.php」もパーツ化したモノの1つです。
パーツ化したテンプレートをテンプレートパーツと呼びます。
テーマを作る上で必ず使うことなので、とても重要な手法です。
パーツ化してみる
ここで紹介するのは、ボクの作るテーマでありがちなパターンです。
トップページ用のテンプレ―ト「front-page.php」と一覧ページ用の共通テンプレート「index.php」があり、トップページには最新の投稿を5件だけ表示させているとします。
■front-page.php
<?php $featured_posts = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 5 //取得記事件数
));
while($featured_posts->have_posts()):
$featured_posts->the_post();?>
<article id="post-<?php the_ID();?>" <?php post_class();?>>
<header class="entry-header">
<h1 class="entry-title"><a href="<?php the_permalink();?>"><?php the_title();?></a></h1>
</header>
<div class="entry-content">
<?php the_excerpt();?>
</div>
</article>
<?php endwhile;
wp_reset_postdata();?>
■index.php
<?php while(have_posts()):
the_post();?>
<article id="post-<?php the_ID();?>" <?php post_class();?>>
<header class="entry-header">
<h1 class="entry-title"><a href="<?php the_permalink();?>"><?php the_title();?></a></h1>
</header>
<div class="entry-content">
<?php the_excerpt();?>
</div>
</article>
<?php endwhile;?>
共通する部分をパーツ化する
ループ内の「<article>~</article>」の内容は一緒ですよね。
ですので、共通する「<article>~</article>」の部分をパーツ化して「content.php」を作ります。
■content.php
<article id="post-<?php the_ID();?>" <?php post_class();?>>
<header class="entry-header">
<h1 class="entry-title"><a href="<?php the_permalink();?>"><?php the_title();?></a></h1>
</header>
<div class="entry-content">
<?php the_excerpt();?>
</div>
</article>
「get_template_part()」でテンプレートパーツを読み込む
パーツ化したファイルを読み込むには「get_template_part()」を使います。
■front-page.php
<?php $featured_posts = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 5 //取得記事件数
));
while($featured_posts->have_posts()):
$featured_posts->the_post();
get_template_part('content');
endwhile;
wp_reset_postdata();?>
■index.php
<?php while(have_posts()):
the_post();
get_template_part('content');
endwhile;?>
これで「content.php」を修正するだけで、「front-page.php」「index.php」のどちらにも修正内容が反映されます。
最後にまとめ
パーツ化することは、メンテナンスや管理が楽になって、とても便利です。
一方で、やりすぎると、複雑化して、逆に管理しにくくなることもあるので注意が必要です。
同じ修正作業を複数のファイルをまたいで行わないようにする。
ボクが気を付けているのはこの1点だけかもしれません。