WordPress   

Load custom page templates from a custom folder in WordPress

The following snippet can be used if you want to load some templates from a custom folder. It works without selecting the custom Template in the edit page screen.  It loads the page templates from the custom folder in the following two formats.

theme_directory/tools/slug.php

theme_directory/tools/id.php

You can set the different custom templates for every page according to their slug or ID. If the slug or the ID of the current page does not match the template name then it follows the default template hierarchy of WordPress

Example – Suppose you want to store some custom templates in the custom folder named services-templates.

  • Create a folder named services-templates in your theme directory and put some templates in it, like website-design.php, digital-marketing.php.
  • Remember that the template name must match with the page slug or page id. In this case, it’s website-design and digital-marketing. These two are the slugs of the pages for which we created custom templates in the first step.

Note – For the above example to work, you need to replace tools with the services-templates in the following code snippet.

 

// Load custom template for tools from tools folder
function load_custom_template_from_folder() {
    $id = get_queried_object_id();
    $template = get_page_template_slug();
    $pagename = get_query_var('pagename');
    if ( ! $pagename && $id ) {
        $post = get_queried_object();
        if ( $post )
            $pagename = $post->post_name;
    }
    $templates = array();
    if ( $template && 0 === validate_file( $template ) )
        $templates[] = $template;
    if ( $pagename )
        $templates[] = "tools/$pagename.php";
    if ( $id )
        $templates[] = "tools/$id.php";
    $templates[] = 'page.php';
    $template = locate_template( $templates );
    return $template;
}
add_filter( 'page_template', 'load_custom_template_from_folder' );
Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us