2026年5月20日
2026年5月20日
WordPressのget_template_part()を活用する方法
はじめに
get_template_part() はWordPressのテンプレートを小さなパーツに分割して再利用するための関数です。ヘッダー・フッター・カード・サイドバーなどを共通パーツとして管理でき、get_header() や get_footer() と同じ原理で動作します。子テーマ対応も自動で行われます。
症状・原因
- 同じHTMLを複数のテンプレートにコピペしている
- テンプレートのパーツを変数によって切り替えたい
- 子テーマでパーツだけオーバーライドしたい
解決手順
ステップ1:基本的な使い方
// 書式: get_template_part( $slug, $name, $args )
// template-parts/card.php を読み込む
get_template_part('template-parts/card');
// template-parts/card-post.php を読み込む(なければ card.php にフォールバック)
get_template_part('template-parts/card', 'post');
ファイル構成の例:
theme/
├── template-parts/
│ ├── card.php // 汎用カード
│ ├── card-post.php // 投稿用カード
│ ├── card-event.php // イベント用カード
│ └── content-none.php // 投稿なし
├── index.php
├── archive.php
└── single.php
ステップ2:ループ内でパーツを呼び出す
// archive.php
<?php if (have_posts()) : ?>
<div class="post-grid">
<?php while (have_posts()) : the_post(); ?>
<?php
// 投稿タイプによってパーツを切り替え
$type = get_post_type(); // 'post', 'event' など
get_template_part('template-parts/card', $type);
?>
<?php endwhile; ?>
</div>
<?php else : ?>
<?php get_template_part('template-parts/content', 'none'); ?>
<?php endif; ?>
ステップ3:引数($args)で変数を渡す(WP 5.5+)
WordPress 5.5以降、第3引数でパーツに変数を渡せます。
// 呼び出し側
get_template_part('template-parts/card', 'post', [
'show_thumbnail' => true,
'excerpt_length' => 80,
'css_class' => 'featured-card',
]);
// template-parts/card-post.php 側
$args = isset($args) ? $args : [];
$show_thumbnail = $args['show_thumbnail'] ?? true;
$excerpt_length = $args['excerpt_length'] ?? 120;
$css_class = isset($args['css_class']) ? esc_attr($args['css_class']) : '';
?>
<article class="card <?php echo $css_class; ?>">
<?php if ($show_thumbnail && has_post_thumbnail()) : ?>
<?php the_post_thumbnail('medium'); ?>
<?php endif; ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php echo esc_html(my_get_excerpt($excerpt_length)); ?></p>
</article>
ステップ4:子テーマでパーツをオーバーライドする
get_template_part() は自動的に子テーマを優先します。
parent-theme/
└── template-parts/card.php // 親テーマのカード
child-theme/
└── template-parts/card.php // 子テーマのカード(こちらが優先される)
子テーマで template-parts/card.php を作成するだけで、親テーマの同名ファイルより優先して読み込まれます。
ステップ5:パフォーマンスへの影響
get_template_part() は毎回ファイル検索を行います。ループ内で大量に呼び出す場合はキャッシュ効果がありません。
// 代替: locate_template() でパスを1回取得してincludeする(大量ループ時)
$tmpl = locate_template('template-parts/card-post.php');
while (have_posts()) : the_post();
if ($tmpl) include $tmpl; // ファイル検索をスキップ
endwhile;
注意事項
- WP 5.5未満では
$argsが使えません。代わりにset_query_var()+get_query_var()を使いますが、グローバルな名前空間を汚染するため推奨しません - パーツ内で
global $postを参照する場合、the_post()を呼んだ後に読み込めばグローバル$postは正しくセットされています
まとめ
get_template_part('template-parts/card', get_post_type()) でループ内のパーツを投稿タイプ別に切り替えられます。WP 5.5以降の第3引数 $args で変数を渡せます。子テーマの同名ファイルが自動的に優先されるため、親テーマを直接修正せずにカスタマイズできます。