「どのテンプレートにも同じループが並んでる…」 「コードが重複してきて管理が大変!」
そんなあなたへ。今回は、
get_template_part()
を使って共通化・再利用の第一歩を踏み出しましょう!
目次
🎯 今回のゴール
初心者でも理解しやすいように、以下の3つの目的を達成します:
- 投稿ループを
content.php
に切り出して再利用できるようにする
→ コードの重複を減らして、メンテナンスをラクにする get_template_part()
の基本構文をマスターする
→ WordPressのテンプレート呼び出しの基本を学ぶcontent-◯◯.php
を使って、投稿タイプや状況ごとにテンプレートを分けられるようにする
→ 柔軟な表示切り替えができるようになる
なぜテンプレートを分けるの?
複数のテンプレート(例:archive.php
, index.php
, category.php
)に同じようなループを書いていると、以下のような問題が起きます:
- 修正が面倒(すべてのテンプレートに直す必要あり)
- コードが長くなって見通しが悪くなる
💡そんなときに活躍するのが get_template_part()
です!
1. 共通のループを content.php
にまとめよう
✅ まずは今までのループを切り出して content.php
に保存
📄 content.php
<article <?php post_class(); ?>>
<a href="<?php the_permalink(); ?>">
<?php if (has_post_thumbnail()) : ?>
<!-- サムネイル画像があれば表示 -->
<div class="thumb"><?php the_post_thumbnail('medium'); ?></div>
<?php endif; ?>
<!-- 投稿のタイトルを表示 -->
<h2><?php the_title(); ?></h2>
<!-- 投稿日時を表示 -->
<time datetime="<?php the_time('Y-m-d'); ?>">
<?php the_time(get_option('date_format')); ?>
</time>
<!-- 投稿の抜粋を表示 -->
<p><?php the_excerpt(); ?></p>
</a>
</article>
🔍 補足:
post_class()
は投稿に応じたクラスを自動出力(例:post
,type-post
,category-news
)the_excerpt()
は投稿本文の冒頭を自動で抜粋表示(設定により手動要約も可能)
2. 呼び出し側で get_template_part()
を使おう
✅ archive.php
や index.php
のループ内でこう書き換えます
📄 archive.php(抜粋)
<?php if (have_posts()) : ?>
<div class="post-list">
<?php while (have_posts()) : the_post(); ?>
<!-- content.php を読み込む(投稿ループ内) -->
<?php get_template_part('content'); ?>
<?php endwhile; ?>
</div>
<?php else : ?>
<p>投稿が見つかりませんでした。</p>
<?php endif; ?>
⚠️ よくある誤用と対策
// ❌ 間違い:拡張子を書いてしまう
get_template_part('content.php');
// ✅ 正しい書き方:拡張子は不要
get_template_part('content');
3. 状況ごとに切り替える:content-◯◯.php
「投稿と固定ページで出力を変えたい」「投稿フォーマットごとに変えたい」そんなときは:
get_template_part('content', 'page');
🔍 WordPressの処理順:
1. content-page.php を探す
2. なければ content.php にフォールバック
この仕組みにより、存在しないテンプレートでもエラーにならず安全に使い分けできます。
✅ 使用例:固定ページ用テンプレート
📄 page.php
<?php get_header(); ?>
<main>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php get_template_part('content', 'page'); ?>
<?php endwhile; endif; ?>
</main>
<?php get_footer(); ?>
📄 content-page.php
<article <?php post_class(); ?>>
<!-- 固定ページのタイトル -->
<h1><?php the_title(); ?></h1>
<!-- 固定ページの本文 -->
<div class="page-content">
<?php the_content(); ?>
</div>
</article>
4. ファイル構成はこうなる
mytheme/
├── content.php ← 投稿一覧用の共通テンプレート
├── content-page.php ← 固定ページ専用のテンプレート
├── archive.php ← 投稿一覧ページ
├── page.php ← 固定ページ用テンプレート
共通部分が content.php
にまとまることで、テーマ全体の保守性が大幅アップ!
✅ よくあるエラーと対策(補足)
get_template_part()
の引数には 拡張子(.php)を書かない- サブディレクトリにあるテンプレートは
get_template_part('parts/content')
のようにパスで指定 - テンプレート間で変数を受け渡したい場合は
set_query_var()
+get_template_part()
(※応用回で解説)
🧠 まとめ:パーツ化は効率的なテーマ作りへの第一歩
get_template_part()
を使えば、共通テンプレートを 何度でも再利用可能- 投稿・固定ページ・カスタム投稿など、出力内容の使い分けも簡単
- 今後のテーマカスタマイズや保守にも大きなメリット!
🔜 次回予告:カテゴリー別に表示を変える!条件分岐で賢いテーマ設計
次回は:
- 特定のカテゴリーだけデザインを変えたい
- このページだけレイアウトを変えたい
というケースに役立つ、is_category()
や is_page()
などの 条件分岐タグの使い方を丁寧に解説していきます!