テンプレート階層のカスタマイズ WordPress 4.7

WordPress4.7からテンプレートカスタマイズ用のフィルタ「{$type}_template_hierarchy」が追加される模様です。

従来よりテンプレートのカスタマイズのために使われているフィルターは「template_include」「{$type}_template」が有名ですが

いずれも、テンプレート階層の中からテンプレートが決定されたものを、書き換えて他のテンプレートを呼び出すものです。

新しいフィルタ「{$type}_template_hierarchy」は テンプレート階層(配列で記述されたテンプレート階層ファイル名)そのものを書き換えることが出来るため、

例えば、カテゴリーのテンプレート階層は category-slug.php , category-id.php , category.php, archive, index.php ですが、
これらのテンプレート名が格納されている 配列を 新しいフィルタ「{$type}_template_hierarchy」で操作できるという事です。

一般的には、この辺りを変更する必要性は少ないと思いますが、

New Functions, Hooks, and Behaviour for Theme Developers in WordPress 4.7のコードサンプルを読んでみましょう。

add_filter( 'date_template_hierarchy', function( array $templates ) {
 $year= get_query_var( 'year' );
 array_unshift( $templates, "year-{$year}.php" );
 return $templates;
} );

月次アーカイブ、年次アーカイブなどで その年を検出して、テンプレート配列の最初に year-2016.php を追加するという意味のことが書かれています。

この配列は、次にlocate_template()によって適用すべきテンプレートが決定します。

結果、year-2016.php が、親テーマまたは、チャイルドテーマに存在した場合それが適用され 2016年専用のアーカイブページが表示されることになるでしょう。

テーマ開発や、WEBサイトの運営を行っている人にとっては、強い誘惑になるかもしれません。

しかし、同時に、テンプレート階層はテーマの基本的な動作をつかさどる部分なので、気づかないところで、表示に失敗するかもしれません。

興味のある人は、慎重に

このフックの場所
wp-includes/post-template.php
( template_include フィルタは wp-includes/template-loader.php )
テンプレート階層
テンプレート階層へのリンク

4.7で追加される予定のテンプレート階層フィルタ

embed_template_hierarchy
404_template_hierarchy
search_template_hierarchy
frontpage_template_hierarchy
home_template_hierarchy
taxonomy_template_hierarchy
attachment_template_hierarchy
single_template_hierarchy
page_template_hierarchy
singular_template_hierarchy
category_template_hierarchy
tag_template_hierarchy
author_template_hierarchy
date_template_hierarchy
archive_template_hierarchy
paged_template_hierarchy
index_template_hierarchy
[emulsion_relate_posts]