説明
get_theme_file_path() は、テーマ内のファイルのサーバー上のパスを返す関数です。子テーマにファイルがあれば子テーマ側が優先されます。
基本構文
get_theme_file_path( string $file = '' ): string
引数
$file:テーマ内の相対パス
戻り値
ファイルの絶対パス。
使い方(サンプル)
require get_theme_file_path( 'inc/setup.php' );
注意点
- 親子テーマの両方に同名ファイルがある場合は、子テーマが優先されます。
実務での使いどころ
- 子テーマで上書きできる、PHPファイルの場所を取得するとき。
includeするファイルを、子テーマ優先で読み込むとき。
よくあるミスと対処
- URLが欲しいのに、これを使っている。この関数が返すのは、サーバー上のパス。URLには
get_theme_file_uri()を使う。 - ファイルが存在するかを確認せずに、
requireする。
NG例
require get_template_directory() . '/inc/helper.php'; // 子テーマで上書きできない
OK例
$file = get_theme_file_path( '/inc/helper.php' );
if ( file_exists( $file ) ) {
require $file;
}
使い分け早見表
| 関数 | 返すもの |
|---|---|
get_theme_file_path() |
子テーマにあれば子テーマ、なければ親テーマの、ファイルのパス |
get_theme_file_uri() |
同じ規則での、URL |
get_template_directory() |
親テーマのパス |
関連項目
get_theme_file_uri()、get_stylesheet_directory()
公式リファレンス:get_theme_file_path() | Function | WordPress Developer Resources

コメント