ヘッダーやカードのような、テーマの中の部品のファイルを読み込みます。子テーマに同じ名前のファイルがあれば、そちらが先に使われます。
書き方
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():ファイルの場所だけを探す



