ワードプレスのget_theme_file_uri関数の使用方法・解説

概要

get_theme_file_uri 関数は、テーマ内にあるファイルのURIを取得するための便利な関数です。この関数は、テーマのリソース(CSS、JavaScript、画像など)を出力する際によく使用されます。具体的には以下のような機能の実装に利用されます:

  1. カスタムCSSやJavaScriptファイルの読み込み
  2. 画像やフォントファイルのURL生成
  3. テーマ設定オプションで使用するファイルパスの取得
  4. AJAXリクエストでのテーマ内リソース参照
  5. テーマ内のテンプレートファイルからのスタイルシートの呼び出し
  6. 管理画面でのテーマ設定ページの作成
  7. サポートするビジュアルエディタのスタイルシートの追加
  8. 子テーマでの親テーマファイルへの参照

構文

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を追加するためのコードです。

この関数について質問する


上の計算式の答えを入力してください