概要
get_theme_file_uri
関数は、テーマ内にあるファイルのURIを取得するための便利な関数です。この関数は、テーマのリソース(CSS、JavaScript、画像など)を出力する際によく使用されます。具体的には以下のような機能の実装に利用されます:
- カスタムCSSやJavaScriptファイルの読み込み
- 画像やフォントファイルのURL生成
- テーマ設定オプションで使用するファイルパスの取得
- AJAXリクエストでのテーマ内リソース参照
- テーマ内のテンプレートファイルからのスタイルシートの呼び出し
- 管理画面でのテーマ設定ページの作成
- サポートするビジュアルエディタのスタイルシートの追加
- 子テーマでの親テーマファイルへの参照
構文
get_theme_file_uri( $path = '' );
パラメータ
- $path (string, optional) – 取得するファイルへの相対パス。指定しない場合はテーマのURIが返されます。
戻り値
- (string) 指定されたパスを持つファイルのURI、もしくはテーマのURI。
使用可能なバージョン
- WordPress 4.7.0 以降
コアファイルのパス
- wp-includes/theme.php
関連する関数
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | 〇 |
after_setup_theme | 〇 |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head | 〇 |
サンプルコード
サンプル1: CSSを読み込む
function my_theme_enqueue_styles() {
wp_enqueue_style('theme-style', get_theme_file_uri('/style.css'));
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');
このサンプルコードは、テーマのstyle.css
を読み込むためのもので、wp_enqueue_scripts
アクションにフックしています。
サンプル2: JavaScriptファイルを読み込む
function my_theme_enqueue_scripts() {
wp_enqueue_script('theme-script', get_theme_file_uri('/js/script.js'), array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');
テーマのjs/script.js
ファイルを読み込む例で、jQueryに依存し、フッターで読み込まれます。
サンプル3: カスタム画像を出力する
<img src="<?php echo get_theme_file_uri('/images/logo.png'); ?>" alt="サイトロゴ">
このコードは、テーマ内のimages/logo.png
のURIを取得し、画像を出力します。
サンプル4: AJAXリクエストでのファイル参照
add_action('wp_ajax_my_ajax', 'my_ajax_function');
function my_ajax_function() {
$response = array(
'image_url' => get_theme_file_uri('/images/ajax-image.png')
);
wp_send_json($response);
}
AJAXリクエストのレスポンスとして、テーマ内の画像URLを返す例です。
サンプル5: 管理画面のスタイルを追加
function my_admin_styles() {
wp_enqueue_style('admin-styles', get_theme_file_uri('/admin/admin-style.css'));
}
add_action('admin_enqueue_scripts', 'my_admin_styles');
管理画面に独自スタイルのCSSを追加するためのコードです。