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

説明

get_theme_file_uri() は、テーマ内のファイルのURLを返す関数です。子テーマにファイルがあれば子テーマ側が優先されます。

基本構文

get_theme_file_uri( string $file = '' ): string

引数

  • $file:テーマ内の相対パス

戻り値

ファイルのURL。

使い方(サンプル)

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

注意点

  • 子テーマになければ、親テーマのファイルが使われます。
  • WordPress 4.7 以降で使えます。

実務での使いどころ

  • 子テーマで上書きできる、CSSや画像のURLを作るとき。
  • 親テーマと子テーマの、どちらにあるかを意識せずに、ファイルのURLを取得するとき。

よくあるミスと対処

  • get_template_directory_uri() を使い、子テーマで同じファイルを用意しても、反映されない。
  • 先頭に / を付け忘れる。get_theme_file_uri( '/img/logo.png' ) のように、先頭にスラッシュを付ける。

NG例

$url = get_template_directory_uri() . '/img/logo.png'; // 子テーマの画像に切り替わらない

OK例

$url = get_theme_file_uri( '/img/logo.png' );

使い分け早見表

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

関連項目

get_theme_file_path()、get_template_directory_uri()

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

コメント

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