私の最近のプロジェクトでは、何十ものカスタム分類法、いくつかの投稿タイプ、コンテンツなどを含み、さまざまな作成者またはタグに対してさまざまなテンプレートが必要なWebサイトを扱っています。
今のところ、私のテンプレートフォルダにはテンプレート用に約70個のphpファイルがありますが、これは非常にわかりにくいです。
私は、27のようないくつかのテーマがテンプレートファイルをフォルダに保存し、それらを次のようにループで呼び出すことに成功したことに気づきました:
get_template_part( 'template-parts/post/content', get_post_format() );
しかし、これはループの中です。私のテンプレートは全く異なっているので、私は上記の解決策を使うことができません、なぜなら私はループの一部ではない何かを変更するために条件式を使う必要があるからです。
たとえば、投稿タイプが3つある場合は、3つのテンプレートファイルを保存する必要があります。
single-type1.php
、single-type2.php
およびsingle-type3.php
。
これらのテンプレートは、ループの内側と外側の両方で(まったく異なるサイドバーであっても)まったく異なるため、single.php
を作成してループ内の適切な投稿タイプを呼び出すことはできません。
テーマテンプレートのフォルダ内に直接保存する以外に、カスタムテンプレートファイルについてWordPressに対処する方法はありますか。
ページテンプレートはテーマ内のpage-templates
またはtemplates
サブディレクトリに格納できますが、これはカスタム投稿タイプまたは分類法テンプレートには適用されません。
幸いなことに、ロードされるテンプレートを変更するためにtemplate_include
フィルタを使用することができます。以下の例では、テンプレートファイルは/theme-name/templates/
ディレクトリに格納されています。
/**
* Filters the path of the current template before including it.
* @param string $template The path of the template to include.
*/
add_filter( 'template_include', 'wpse_template_include' );
function wpse_template_include( $template ) {
// Handle taxonomy templates.
$taxonomy = get_query_var( 'taxonomy' );
if ( is_tax() && $taxonomy ) {
$file = get_theme_file_path() . '/templates/taxonomy-' . $taxonomy . '.php';
if ( file_exists( $file ) ) {
$template = $file;
}
}
// Handle post type archives and singular templates.
$post_type = get_post_type();
if ( ! $post_type ) {
return $template;
}
if ( is_archive() ) {
$file = get_theme_file_path() . '/templates/archive-' . $post_type . '.php';
if ( file_exists( $file ) ) {
$template = $file;
}
}
if ( is_singular() ) {
$file = get_theme_file_path() . '/templates/single-' . $post_type . '.php';
if ( file_exists( $file ) ) {
$template = $file;
}
}
return $template;
}
すべての分類法に1つのテンプレートを使用してtaxonomy.phpという名前を付けるか、関数ファイルでtemplate_includeを使用します。
add_filter( 'template_include', 'tax_page_template', 99 );
function tax_page_template( $template ) {
if ( is_tax( 'taxonomy' ) ) {
$new_template = locate_template( array( 'your-tax.php' ) );
if ( '' != $new_template ) {
return $new_template ;
}
}
return $template;
}
使用しているテーマに応じて、[ページ属性]> [テンプレート]ドロップダウンメニューで1つのテンプレートを使用し、テーマ設定を使用して各テンプレートを変更することもできます。