LucyとRuby

WordPress:テーマフォルダのディレクトリ(パス)を取得する方法

WordPressでテーマフォルダのディレクトリを取得する方法を説明します。

get_template_directory()はパスを取得

get_template_directory()はテーマのルートディレクトリの「パス」を返します。具体的な返り値の例は下記。

<php?
echo get_template_directory();
// 結果
// C:\xampp\htdocs\wordpress/wp-content/themes/theme_name

スラッシュとバックスラッシュについて

上記の結果をよく見るとパス区切りの記号が前半はバックスラッシュ(\)だったのが、wordpressフォルダ以降はスラッシュ(/)に変化している。おそらく前半はWindowsシステムでパスを取得していて、Windowsのパス区切り記号がバックスラッシュ(\)だからかな?wordpress以下の階層はphpとかwordpress自身によって取得しているからスラッシュ(/)になっているとか?正確なところはわからないけどたぶんそんなところだと思う。ウェブサイトを表示する程度の用途ならば\/が混在していても問題なく動作するようである。

get_template_directory()はphpでテンプレートファイルやファンクションファイルなどを読み込む時のパス指定などに使います。下記はテーマのルートディレクトリにあるmy_template1.phpを読み込む場合の使用例。

<?php
include_once(get_template_directory() . '/my_template1.php');

get_template_directory_uri()はuriを取得

get_template_directory_uri()はテーマのルートディレクトリの「uri」を返します。具体的な返り値の例は下記。

<php?
echo get_template_directory_uri();
// 結果
// http://localhost/wordpress04/wp-content/themes/theme_name

get_template_directory_uri()はweb上で画像を表示する場合にその画像のuriを指定する場合などに使います。下記はmy_image.jpgを表示する場合の使用例。

<?php
<img src="<?php echo get_template_directory_uri(); ?>/my_image.jpg" alt="">
// 出力されるhtml
// <img src="http://localhost/wordpress/wp-content/themes/theme_name/my_image.jpg" alt="">

コードとしてして書き出す場合にはechoを書き忘れないようにしましょう。

補足:bloginfo('template_directory')は非推奨

テーマのルートディレクトリを取得する方法は他にbloginfo('template_directory')get_bloginfo('template_directory')がありますが、これらは現在は非推奨(日本語版Codex)とされているので使わないようにしましょう。

post no. 307

Comments