説明
get_template_directory() は、現在のテーマ(親テーマ)のサーバー上のパスを返す関数です。
基本構文
get_template_directory(): string
引数
引数はありません。
戻り値
テーマディレクトリの絶対パス。
使い方(サンプル)
require_once get_template_directory() . '/inc/helpers.php';
注意点
- URLではなくファイルパスです。
requireやincludeに使います。 - 子テーマを使っている場合も親テーマのパスを返します。
実務での使いどころ
- 親テーマの、PHPファイルの場所を指定して読み込むとき(
require・include)。
よくあるミスと対処
- URLが欲しいのに、これを使っている。この関数が返すのは、サーバー上のファイルのパス。URLには
get_template_directory_uri()を使う。 - 子テーマを使っているのに、子テーマのファイルを読み込むつもりで、これを使っている。常に親テーマの場所を返す。
NG例
echo '<img src="' . get_template_directory() . '/img/logo.png">'; // パスなので、画像が表示されない
OK例
require_once get_template_directory() . '/inc/helper.php';
echo '<img src="' . esc_url( get_template_directory_uri() . '/img/logo.png' ) . '">';
使い分け早見表
| 関数 | 返すもの |
|---|---|
get_template_directory() |
親テーマのサーバー上のパス |
get_stylesheet_directory() |
使用中のテーマのサーバー上のパス |
get_template_directory_uri() |
親テーマのURL |
関連項目
get_stylesheet_directory()、get_template_directory_uri()、get_theme_file_path()
公式リファレンス:get_template_directory() | Function | WordPress Developer Resources

コメント