WordPressのget_template_part()の使い方とメリット解説

WordPressテーマを効率よく構築・管理するために欠かせないのが、get_template_part()
です。この関数を使えば、テンプレートファイルを部品化して再利用でき、保守性の高いテーマづくりが実現します。
Contents
get_template_part()とは?
get_template_part()
は、指定したテンプレートパーツを読み込むための関数です。例えば、共通の投稿ループやセクションを別ファイルに分けておき、それを必要な場所で読み込めます。
基本構文:
<?php get_template_part( 'template-parts/content', 'single' ); ?>
この例では、template-parts/content-single.php
が読み込まれます。
ファイル構成の例
theme-name/
├── template-parts/
│ ├── content.php
│ └── content-single.php
├── single.php
├── index.php
single.php
内で get_template_part( 'template-parts/content', 'single' );
を使えば、投稿本文の出力部分だけを分けて管理できます。
よくある使い方
投稿ループの分離:
<?php get_template_part( 'template-parts/content', get_post_type() ); ?>
投稿タイプに応じて content-post.php
や content-page.php
を自動で読み込む方法も便利です。
セクションの共通化:
例えば、ヒーローセクションやCTAをテンプレートパーツとして使い回すことができます。
<?php get_template_part( 'template-parts/hero' ); ?>
メリットまとめ
- コードの再利用性が高まる
- 保守性・可読性の向上
- テーマの構造が整理される
補足:locate_template()との違い
get_template_part()
は内部的にlocate_template()
を使っていますが、require
の代わりにload_template()
で読み込む点が違います。
共通パーツをうまく分離することで、WordPressテーマ開発はぐっと効率的になります。テンプレート階層や条件分岐と組み合わせると、さらに自由度の高いテーマづくりが可能です。