概要
get_template_directory
関数は、現在アクティブなテーマのディレクトリのパスを取得するために使用されます。この関数は、テーマのリソース(画像、スタイルシート、スクリプトなど)にアクセスする際によく使用されます。具体的には、以下のようなシチュエーションで便利です:
- テーマ内のスタイルシートやスクリプトのパスを指定する
- テンプレートパーツを動的に読み込む
- テーマ画像のURLを生成する
- カスタム関数書をファイルから読み込む
- 言語ファイルのパスを指定する
- プラグインによるテーマのカスタマイズを補助する
- 子テーマのリソースにアクセスする
- テーマの設定ファイルを含める
構文
get_template_directory();
パラメータ
この関数にはパラメータはありません。
戻り値
この関数は、アクティブなテーマの絶対パスを示す文字列を返します。
関連する関数
使用可能なバージョン
この関数は、WordPress 2.1.0 から使用可能です。
コアファイルのパス
get_template_directory
関数は、wp-includes/theme.php
に含まれています。
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | 〇 |
after_setup_theme | 〇 |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | 〇 |
get_header | 〇 |
wp_head | 〇 |
サンプルコード
サンプルコード1: スタイルシートの読み込み
function my_theme_enqueue_styles() {
wp_enqueue_style('main-style', get_template_directory() . '/style.css');
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');
このサンプルコードは、アクティブなテーマのスタイルシートを読み込むものです。
サンプルコード2: 画像のパス生成
<img src="<?php echo get_template_directory(); ?>/images/logo.png" alt="Logo">
このサンプルコードは、コアディレクトリ内の画像のパスを生成し、それを使用して画像を表示します。
サンプルコード3: テンプレートパーツの読み込み
get_template_part('template-parts/content', 'page');
このサンプルコードは、template-parts/content-page.php
を読み込むためのものです。この関数の内部で get_template_directory
が実行されて、必要なファイルパスが決定されます。
サンプルコード4: カスタム関数の読み込み
require_once get_template_directory() . '/inc/custom-functions.php';
このサンプルコードは、カスタム関数が定義されたファイルを読み込むために使用されます。
サンプルコード5: AJAX処理での使用
add_action('wp_ajax_my_custom_ajax', 'my_custom_ajax_function');
function my_custom_ajax_function() {
// テンプレートディレクトリを利用
$template_path = get_template_directory() . '/ajax-response.php';
include($template_path);
wp_die();
}
このサンプルコードは、AJAXリクエストの際に特定のテンプレートを読み込むために get_template_directory
を使用しています。