【WordPress】get_header()・get_footer()などのテンプレートタグまとめ+include/requireとの違いも解説!

WordPressでテーマ開発をしていると、get_header()
や get_footer()
をはじめとするテンプレートタグは非常によく使われます。
また、PHPの include()
や require_once()
でもファイルを読み込むことができますが、これらはどう違うのでしょうか?
この記事では、WordPressのテンプレートタグの使い方と、PHP標準関数との違いをわかりやすくまとめてご紹介します。
Contents
テンプレートタグまとめ
get_header()
<?php get_header(); ?>
header.php
を読み込む- ページ上部(
<head>
やナビゲーション)によく使用される - 引数を指定すると
header-○○.php
を読み込むことも可能
<?php get_footer(); ?>
footer.php
を読み込む- フッター共通部分に使う
get_footer('sub')
→footer-sub.php
を読み込む
<?php get_sidebar(); ?>
- サイドバー領域の共通パーツを読み込む(
sidebar.php
) get_sidebar('shop')
→sidebar-shop.php
などで切り替え可能
get_template_part()
<?php get_template_part('content', 'single'); ?>
content-single.php
やcontent.php
を読み込む- ループ内で記事レイアウトを切り分けたいときに便利
- 再利用性の高いテンプレートパーツにおすすめ
locate_template() + load_template()
<?php
$template = locate_template('components/banner.php');
if ($template) {
load_template($template);
}
?>
- より柔軟にテンプレートファイルを探して読み込める
- 条件分岐と組み合わせてカスタムな動きが可能
- 子テーマ対応などにも使われる
2. PHPの include() / require() との違い
項目 | WordPressテンプレートタグ | include()/require() |
---|---|---|
WordPressのテーマ構造と連携 | ◎(子テーマ対応など) | × |
条件付きテンプレート読み込み | ◎(get_template_part など) | △(条件分岐は可能だが手動) |
エラーハンドリング | get系は失敗しても止まらない | require系は失敗するとエラー |
テーマ階層への対応 | ◎(locate_template使用) | ×(指定したパスのみ) |
推奨度 | ◎(WordPress開発推奨) | △(補助的に使用) |
include()
<?php include('parts/banner.php'); ?>
- 指定したパスのファイルを読み込む
- ファイルが見つからないと warning が出るが処理は継続
require_once()
<?php require_once('functions/custom.php'); ?>
- 一度だけ読み込む(重複読み込み防止)
- ファイルが見つからないと fatal error で処理停止
3. 結論:テーマ開発にはテンプレートタグが基本!
PHPの include()
や require()
は便利ですが、WordPressのテーマ開発においては get_header()
などのテンプレートタグを使うのが基本です。
理由は以下の通り:
- テーマ階層・子テーマに対応している
- 管理画面からのカスタマイズやプラグイン連携に強い
- 他の開発者との協業でもルールが明確になる
まとめ
使用場面 | 推奨関数 |
---|---|
header.php を読み込みたい | get_header() |
再利用可能なパーツを使い回したい | get_template_part() |
テンプレートファイルの場所を柔軟に指定したい | locate_template() + load_template() |
単純なPHPファイル読み込み | include() や require_once() (補助的に) |
参考リンク
- get_header() – Function – WordPress Developer Resources
- get_template_part() – Function | Developer.WordPress.org
- PHP公式マニュアル – include