get_template_part():テーマの部品のファイルを読み込む(WordPress)

ヘッダーやカードのような、テーマの中の部品のファイルを読み込みます。子テーマに同じ名前のファイルがあれば、そちらが先に使われます。

書き方

get_template_part( string $slug, ?string $name = null, array $args = array() ): void|false
  • $slug:ファイルの名前(拡張子なし)。例 'parts/card'
  • $name(省略できる):付けると {slug}-{name}.php を先に探します。なければ {slug}.php。
  • $args(省略できる):部品のファイルに渡す値。部品の中では $args で受け取ります(WordPress 5.5 から)。
  • ファイルが見つからないと false を返します。

使い方の例

// 一覧のループの中で、投稿タイプごとにカードを分ける
// parts/card-product.php があればそれ、なければ parts/card.php
while ( have_posts() ) {
	the_post();
	get_template_part( 'parts/card', get_post_type(), array( 'show_date' => true ) );
}
// parts/card.php の中
<?php if ( ! empty( $args['show_date'] ) ) : ?>
	<time><?php echo esc_html( get_the_date() ); ?></time>
<?php endif; ?>

よくある間違い

  • 拡張子 .php を付けて書いてしまう(parts/card.php.php を探して見つからない)。
  • 部品のファイルでは、呼んだ側の変数($foo など)は使えません。値は $args で渡します。
  • テーマの外のファイル(プラグインのファイルなど)は読み込めません。そのときは require や load_template() を使います。

関連する関数

  • get_header()・get_footer()・get_sidebar():決まった部品を読み込む
  • locate_template():ファイルの場所だけを探す

逆引きリファレンスの一覧へ

サイドバー

よく使うカスタマイズ

最近の記事

  1. Fstyle Final Output Replacer のルールの一覧(generator タグを消す 2 つのルール)

Profile

PAGE TOP