概要
get_singular_template
フィルタは、WordPressのテーマにおいて、シングル投稿や固定ページのテンプレートパス名をカスタマイズするために使用されるフィルタです。このフィルタは、特定の投稿タイプやページに基づいて異なるテンプレートを使用する際に特に便利です。
一般的に、以下のような機能を実装する際に利用されます:
- 特定の投稿タイプに対して独自のテンプレートを適用する。
- カスタムフィールドに基づいてテンプレートを変更する。
- ユーザーの権限やロールによって異なるテンプレートを使用する。
- プラグインに依存して異なるテンプレートを使用する。
- 異なる言語や地域に応じてテンプレートを変更する。
- テンプレートのテーマスラグを基に選択する。
- スラッグやIDに応じて特定のテンプレートを使用する。
- デバイスや画面サイズに基づいて異なるテンプレートを適用する。
構文
add_filter('get_singular_template', 'custom_singular_template_function');
パラメータ
$template
: 現在選択されているテンプレートのパス名(文字列)。
戻り値
- カスタマイズされたテンプレートのパス名(文字列)。
関連する関数
使用可能なバージョン
- このフィルタはWordPress 4.1.0以降で利用可能です。
コアファイルのパス
wp-includes/template.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: カスタムテンプレートを使用する
add_filter('get_singular_template', function($template) {
if (is_singular('custom_post_type')) {
return get_template_directory() . '/custom-template.php';
}
return $template;
});
このコードは、特定のカスタム投稿タイプに対して独自のテンプレートを指定します。
サンプルコード2: カスタムフィールドに基づくテンプレート変更
add_filter('get_singular_template', function($template) {
$custom_field_value = get_post_meta(get_the_ID(), 'custom_field', true);
if ($custom_field_value === 'value1') {
return get_template_directory() . '/template-value1.php';
}
return $template;
});
このコードは、カスタムフィールドの値に基づいて異なるテンプレートを適用します。
サンプルコード3: ユーザーの権限による変更
add_filter('get_singular_template', function($template) {
if (current_user_can('administrator')) {
return get_template_directory() . '/admin-template.php';
}
return $template;
});
このコードでは、管理者権限を持つユーザーに対して特別なテンプレートを使用します。
サンプルコード4: 言語に応じたテンプレート選択
add_filter('get_singular_template', function($template) {
if (function_exists('pll_current_language') && pll_current_language() === 'ja') {
return get_template_directory() . '/template-ja.php';
}
return $template;
});
このコードにより、現在の言語が日本語であれば異なるテンプレートを指定します。
サンプルコード5: デバイスによるテンプレートの適用
add_filter('get_singular_template', function($template) {
if (wp_is_mobile()) {
return get_template_directory() . '/mobile-template.php';
}
return $template;
});
このコードは、ユーザーがモバイルデバイスを使用している場合に特定のテンプレートを適用します。
これらのサンプルコードはすべて著作権フリーであり、一般的な使用法に基づいています。引用元ページはありませんが、具体的な設定に応じて適切なテンプレートを提供することを目的としています。