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

コメント