WordPress Custom Page Template in a different directory

Is it possible to have a custom page template in a different folder?

I’m setting up a little framework for WordPress that I can use over and over for themes and just for the sake of being tidy I want to put custom page templates inside a different folder rather than the root of the theme directory.

Read More

How would one go about this?

Related posts

Leave a Reply

2 comments

  1. WordPress uses get_page_template() to determine the template file to use which can be altered by filters:

    //for pages
    add_filter( 'page_template', 'My_custom_page_template' );
    function My_custom_page_template( $page_template )
    {
        if ( is_page( 'my-custom-page-slug' ) ) {
            $page_template = 'pathto/custom-page-template.php';
        }
        return $page_template;
    }
    
    //for posts 
    add_filter( 'single_template', 'My_custom_page_template' );
    function My_custom_page_template( $single_template )
    {
        if ( is_single( 'my-custom-page-slug' ) ) {
            $single_template = 'pathto/custom-post-template.php';
        }
        return $single_template;
    }
    
  2. I wanted the same functionality as this. It seemed as though it is impossible to do this without core changes, but i managed to get it working – in a slightly different way.

    Create a page template in the root of your Theme, call it themename-page-loader.php

    In that file put the following code:

    /**
     * Template Name: ThemeNAME Page Loader
     */
    
    global $post;
    
    // Define the post_name and the file name of the current page
    $pslug = $post->post_name;
    $pname = $pslug . '.php';
    
        // Load the TEMPLATE file in your custom directory
        require_once( TEMPLATEPATH . '/views/' . $pname );
    

    Then in your theme root, create a folder for your pages, in this example i called mine views. Inside this folder you put your page templates, just make sure the file name is the same as the page name you set in WP_ADMIN.