Понадобилось создавать много лендинг-страниц с индивидуальными шаблонами по принципу page-custom-page-slug-name.php, но при этом не засорять корневую папку шаблона кучей файлов. Нашелся вот такой костыль в виде функции 🙂
When you look at the source code, the tag template is loaded as follow in template hierarchy
elseif ( is_tag() && $template = get_tag_template() ) :
inwp-includes/template-loader.php
get_tag_template()
usesget_query_template()
which useslocate_template()
- which loads the tag template according to hierarchy from the theme root folder
So, moving your templates to a sub-folder will not work out-of-the-box.
get_query_template()
however have a filter (apply_filters( "{$type}_template", $template )
) that we can use to change this behavior and load ourtag-{$tag->slug}.php
from a subfolderSo, we should do the following
- Check if our
tag-{$tag->slug}.php
exists in our subfolder of choice- Load our
tag-{$tag->slug}.php
from subfolder if it exists- Load default templates from the hierarchy if
tag-{$tag->slug}.php
does not exists in a subfolderSomething like the following will work
add_filter( 'tag_template', function ( $template ) { $tag = get_queried_object(); // Alternative path to desired template $alternative_template = locate_template( "custom-sub-folder/tag-{$tag->slug}.php" ); // Change subfolder name // If we do have "tag-{$tag->slug}.php" in a subfolder, load "subfolder/tag-{$tag->slug}.php" if ( $alternative_template ) return $template = $alternative_template; // If we don't have a "tag-{$tag->slug}.php", load templates according to hierarchy return $template; });
и этот пример для тэгов был найден тут, а для страниц код будет выглядеть вот так:
add_filter( 'page_template', function ( $template ) { $page = get_queried_object(); // Alternative path to desired template $alternative_template = locate_template( "landing-pages/page-{$page->post_name}.php" ); // Change subfolder name // If we do have "page-{$page->post_name}.php" in a subfolder, load "landing-pages/page-{$page->post_name}.php" if ( $alternative_template ) return $template = $alternative_template; // If we don't have a "page-{$page->post_name}.php", load templates according to hierarchy return $template; });
вот и все 🙂 теперь смело можем складывать файлы шаблонов страниц в папку landing-pages