get_template_directory_uri() の使い方|説明・引数・注意点

説明

get_template_directory_uri() は、現在のテーマ(親テーマ)のURLを返す関数です。画像やCSS・JSの読み込みに使います。

基本構文

get_template_directory_uri(): string

引数

引数はありません。

戻り値

テーマディレクトリのURL。末尾スラッシュなし。

使い方(サンプル)

echo esc_url( get_template_directory_uri() . '/images/logo.png' );

注意点

  • 子テーマを使っている場合でも、親テーマのURLを返します。子テーマ側は get_stylesheet_directory_uri() です。
  • 末尾にスラッシュは付きません。

実務での使いどころ

  • 親テーマの、CSSや画像などのファイルのURLを作るとき。

よくあるミスと対処

  • 子テーマを使っているのに、子テーマのファイルのURLを取りたくて、これを使っている。この関数は、常に親テーマのURLを返す。子テーマには get_stylesheet_directory_uri() を使う。
  • 末尾に / が付かないことを忘れ、ファイル名をつなげて壊れる。/css/style.css のように、先頭にスラッシュを付けてつなげる。

NG例

// 子テーマのファイルを読み込むつもり
wp_enqueue_style( 'child', get_template_directory_uri() . '/style.css' );

OK例

wp_enqueue_style( 'child', get_stylesheet_directory_uri() . '/style.css' );

使い分け早見表

関数 返すURL
get_template_directory_uri() 親テーマのURL
get_stylesheet_directory_uri() 使用中のテーマ(子テーマなら子テーマ)のURL
get_theme_file_uri() 子テーマにあれば子テーマ、なければ親テーマのファイルのURL

関連項目

get_stylesheet_directory_uri()、get_template_directory()、get_theme_file_uri()

公式リファレンス:get_template_directory_uri() | Function | WordPress Developer Resources

コメント

タイトルとURLをコピーしました