概要
get_theme_file_path
関数は、テーマ内にあるファイルのパス名を取得するための非常に便利な関数です。この関数は、特定のファイルへの正しいパスを取得することで、テーマのファイルへのアクセスを容易にします。主に以下のような機能を実装する際によく使用されます。
- テンプレートファイルの読み込み
- スタイルシートやスクリプトファイルの参照
- 画像やメディアファイルのパス取得
- カスタムエラーページの読み込み
- テーマ独自の設定ファイルの読み込み
- 国際化対応のリソースのパス指定
- 子テーマと親テーマのファイル管理
- カスタムテンプレートの呼び出し
構文
get_theme_file_path( $path );
パラメータ
$path
(string) [オプション]: テーマ内のファイルの相対パス。指定しない場合はテーマのルートパスが返されます。
戻り値
テーマ内にあるファイルのパス名を返します。ファイルが存在しない場合は、親テーマのファイルパスを返すことがあります。
関連する関数
- [get_template_directory()]
- [get_stylesheet_directory()]
- [get_theme_file_uri()]
使用可能なバージョン
この関数は、WordPress 4.7以降で使用可能です。
コアファイルのパス
get_theme_file_path
関数は、WordPressのコアファイル内の 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: テンプレートファイルの読み込み
$template_path = get_theme_file_path( 'header.php' );
include( $template_path );
このコードは、テーマの header.php
ファイルのパスを取得し、そのファイルをインクルードしています。
サンプル 2: スタイルシートファイルの参照
$style_path = get_theme_file_path( 'style.css' );
echo '<link rel="stylesheet" href="' . esc_url( $style_path ) . '">';
このコードは、テーマの style.css
ファイルのパスを取得し、スタイルシートとしてHTMLに出力しています。
サンプル 3: 画像ファイルのパス取得
$image_path = get_theme_file_path( 'images/logo.png' );
echo '<img src="' . esc_url( $image_path ) . '" alt="Logo">';
このコードは、テーマ内の images/logo.png
という画像のパスを取得し、画像をHTMLに出力しています。
サンプル 4: 設定ファイルの読み込み
$config_path = get_theme_file_path( 'inc/config.php' );
if ( file_exists( $config_path ) ) {
include( $config_path );
}
このコードは、テーマの設定ファイルである inc/config.php
のパスを取得し、存在する場合にそのファイルをインクルードしています。
サンプル 5: 子テーマのファイルを参照
$child_file_path = get_theme_file_path( 'custom/child-file.php' );
include( $child_file_path );
このコードは、子テーマ内の custom/child-file.php
のパスを取得し、そのファイルをインクルードしています。