Шаблоны страниц в подпапке / Page templates in subfolder


Понадобилось создавать много лендинг-страниц с индивидуальными шаблонами по принципу page-custom-page-slug-name.php, но при этом не засорять корневую папку шаблона кучей файлов. Нашелся вот такой костыль в виде функции 🙂

When you look at the source code, the tag template is loaded as follow in template hierarchy

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 our tag-{$tag->slug}.php from a subfolder

So, 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 subfolder

Something 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