かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

WordPress サブテーマ テーマの絶対パスを取得したい。

WordPressでテーマのディレクトリの絶対パス取得をする方法のメモ
テーマ構成

/themes
   |- /main-theme
   |   |- functions.php
   |- /sub-theme
   |   |- functions.php

テーマディレクトリまでのパスの取得

get_template_directory

テーマのパスを取得するのに get_template_directory() を使っているのをよく見ますが、サブテーマでこの関数を使うと親テーマのディレクトリまでのパスが返されてしまいます。

親テーマ内で使用

<?php // /main-theme/functions.php
echo get_template_directory();
// 出力 => /home/www/wordpress/wp-content/themes/main-theme

子テーマ内で使用

<?php // /sub-theme/functions.php
echo get_template_directory();
// 出力 => /home/www/wordpress/wp-content/themes/main-theme

get_template_directory()は常に親テーマのディレクトリまでのパスが取得される。

get template directory
末尾にスラッシュを付けずに、現在のテーマのディレクトリへの絶対パスを取得します。
子テーマが使用されている場合には、親テーマのディレクトリへの絶対パスが返されます。 子テーマのディレクトリへの絶対パスを取得するには get_stylesheet_directory() をお使いください。
[出典] 関数リファレンス/get template directory - WordPress Codex 日本語版

get_stylesheet_directory

get stylesheet directory
現在のテーマまたは子テーマのスタイルシートディレクトリのパスを取得します。
注: 末尾にスラッシュを含みません。
[出典] 関数リファレンス/get stylesheet directory - WordPress Codex 日本語版

親テーマ内で使用

<?php // /main-theme/functions.php
echo get_stylesheet_directory();
// 出力 => /home/www/wordpress/wp-content/themes/main-theme

子テーマ内で使用

<?php // /sub-theme/functions.php
echo get_stylesheet_directory();
// 出力 => /home/www/wordpress/wp-content/themes/sub-theme

get_stylesheet_directory()を使えばそれぞれのテーマまでのパスが取得することができました!
 

get_stylesheet_directory 親テーマ内のfunctions.phpで実行されても今見ているサイトのテーマまでのパスが取得できるっぽい

WordPressの子テーマは親テーマのfunctions.phpも実行されます。
親テーマのfunctions.phpget_stylesheet_directory()がある時、子テーマから実行されると「現在のテーマ」である子テーマのパスが返されるようです。
これを利用すれば、親テーマに書いておくだけで、子テーマが複数あっても各テーマの設定ファイルを読み込んだりさせることができます。

テーマ構成

/themes
   |- /main-theme
   |   |- functions.php
   |   |- /inc
   |       |- config.php
   |- /sub-theme
   |   |- functions.php
   |   |- /inc
   |       |- config.php

親テーマ(/main-theme/functions.php)

<?php
define('__THEME_DIR__', get_stylesheet_directory());
require_once(__THEME_DIR__ . '/inc/config.php');
  1. 親テーマのサイトを見ている時
    /main-theme/inc/config.php が読み込まれる
  2. 子テーマのサイトを見ている時
    /sub-theme/inc/config.php が読み込まれる

 
WordPressで親テーマ・子テーマを作成する時は、常に親テーマまでの絶対パスを取得したい時はget_template_directory()、動的に現在のテーマまでの絶対パスを取得したい時はget_stylesheet_directory()を使えば良いとお覚えておけば良さそうです。


[参考]