【WordPress】子テーマ・親テーマのディレクトリを取得する方法|style.cssを追加する場合など
WordPressでサイトを作成しているとテーマのディレクトリを取得したい場合があると思います。
今回は、そのテーマのディレクトリを取得する関数の違いなどのまとめとなります。
テーマのディレクトリを取得する関数
テーマのディレクトリを取得する関数には、以下の4つがあります。
絶対パスを取得する関数
- get_template_directory()
- get_stylesheet_directory()
取得するパスの例
/home/user/public_html/wp-content/themes/my_theme
URIを取得する関数
- get_template_directory_uri()
- get_stylesheet_directory_uri()
取得するパスの例
https://example.com/wp-content/themes/my_theme
【子テーマを利用している場合】テーマのディレクトリを取得する関数の違い
子テーマを利用している場合、上記のテーマのディレクトリを取得する関数は、以下のように異なるパスを取得します。
get_template_directory・get_template_directory_uriの場合
get_template_directory()・get_template_directory_uri()は、親テーマの絶対パス・URIを取得します。
get_stylesheet_directory・get_stylesheet_directory_uriの場合
get_stylesheet_directory()・get_stylesheet_directory_uri()は、子テーマの絶対パス・URIを取得します。
また、テーマディレクトリ内のstyle.cssのURIを取得するget_stylesheet_uri()も子テーマのstyle.cssを取得します。
子テーマを利用している場合に、親テーマと子テーマのスタイルシートを追加する例
例えば、子テーマを利用している場合に、親テーマと子テーマのスタイルシートを追加する場合は、functions.phpに以下のソースコードを記述します。
function my_enqueue_styles(){
// 親テーマフォルダ内にあるstyle.cssを追加
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
// 子テーマフォルダ内にあるstyle.cssを追加
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( 'parent-style' ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_styles' );
また、スタイルシート追加するwp_enqueue_style関数については、以下のリンク先を参考にしてみてください。