WordPressのテーマディレクトリへのURLを取得する「get_theme_file_uri」と絶対パスを取得する「get_theme_file_path」

WordPressのテーマディレクトリへのURLを取得する「get_theme_file_uri」と絶対パスを取得する「get_theme_file_path」

WordPressのテーマディレクトリへのURLを取得する「get_theme_file_uri」と絶対パスを取得する「get_theme_file_path」

get_theme_file_uriとget_theme_file_pathは、どちらもテーマディレクトリへのパスを取得するための関数です。WordPress4.7から追加されています。

get_theme_file_uriはテーマディレクトリへのURLを取得し、get_theme_file_pathは絶対パスを取得します。

スポンサードリンク

get_theme_file_uriを使ってテーマディレクトリのURLを取得する方法

get_theme_file_uriは、get_template_directory_uriやget_stylesheet_directory_uriの代替として使用できます。

大きな特徴としては、get_theme_file_uriを使ってファイルのURLを取得する場合、子テーマ側にファイルが存在している場合は子テーマ側のファイルが優先されて読み込まれるという点です。そのため、get_template_directory_uriとget_stylesheet_directory_uriを使い分ける必要がありません。

以下は、imagesフォルダ内のsample.pngを読み込む場合の例です。


//get_template_directory_uriでURLを取得
<img src="<?php echo get_template_directory_uri(); ?>/images/sample.png">

//get_theme_file_uriでURLを取得
<img src="<?php echo get_theme_file_uri( '/images/sample.png' ); ?>">

get_template_directory_uriやget_stylesheet_directory_uriとは、記述方法が少し異なりますね。

ちなみに、子テーマと親テーマの両方に同じファイルがあって、親テーマのファイルを読み込みたい時は、get_parent_theme_file_uriを使います。以下は一例ですが、子テーマのfunctions.phpで親テーマのスタイルを読み込む場合のコードです。


function parent_styles() {
  wp_enqueue_style('parent-style', get_parent_theme_file_uri('/style.css'));
}
add_action( 'wp_enqueue_scripts', 'parent_styles' );

get_theme_file_pathを使ってテーマディレクトリの絶対パスを取得する方法

get_theme_file_pathを使って、テーマディレクトリへの絶対パスを取得するには、以下のように記述します。


//get_template_directoryで絶対パスを取得
require get_template_directory() . '/include/sample.php';

//get_theme_file_pathで絶対パスを取得
require get_theme_file_path('/include/sample.php');

こちらもget_theme_file_uriと同じような記述方法で、子テーマ側のファイルが優先されます。

あとがき

テーマで使える関数も徐々に変化していきますね。

get_theme_file_uriやget_theme_file_pathを使ってパスを指定しておくと、後々のカスタマイズも楽になるかと思います。今のうちからこれらの関数に慣れておきたいですね。

この記事が気に入ったら
いいね!してね♪

Twitter で
スポンサードリンク

関連記事

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です