Blog

【WordPress】get_template_directory_uriとget_stylesheet_directory_uriの違いを整理する

2021.09.14 2021.09.15 WordPress

普通にWordPressテーマを作る場合、get_template_directory_uriとget_stylesheet_directory_uriの違いはあまり問題になりません。

しかい、子テーマを作る場合には注意が必要です。

子テーマでget_template_directory_uriを使って画像を表示しようとすると、うまく表示されなかったり、親テーマの方に格納されている画像が表示されてしまったりするからです。

たぶん多くの人がつまづくポイントではないかと思うのですが、知ってしまえば何のことはない話ですので、今回は両者の違いについて整理しておこうと思います。

get_template_directory_uriとget_stylesheet_directory_uriの違いを整理する

get_template_directory_uri

<img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" alt="">

get_template_directory_uriは親テーマのディレクトリURIを返します。

そのため子テーマでget_template_directory_uriを使うと、子テーマではなく親テーマの画像が表示されたり、子テーマにしかない画像の場合は画像が表示されないということになります。

逆に言うと子テーマでも親テーマにある画像を使いたい場合には、get_template_directory_uriを使えばいいということになります。

get_stylesheet_directory_uri

<img src="<?php echo get_stylesheet_directory_uri(); ?>/images/logo.png" alt="">

get_stylesheet_directory_uriは、スタイルシートが格納されているディレクトリのURIを返します。

子テーマでは子テーマのスタイルシートが格納されているURI(=子テーマディレクトリのURL)が返されるので、子テーマにある画像を表示させたい場合はこちらを使います。

まとめ

以上、get_template_directory_uriとget_stylesheet_directory_uriの違いについてでした。

子テーマを作る場合には必要となる知識なので、しっかり整理して使い分けできればいいかと思います。