Create Page that uses specific template

The question was about how to use a template that is not in the theme’s folder, but in a plugin’s folder. The template needs to be used for a specific page. The need for the answer doesn’t matter. There is a need; how do I do it?

And the answer is to use the template_include filter (see here) . Here’s my explanation of my answer:

The plugin that I am developing creates a page. That page then needs to use a template that the plugin provides. I could do it by

  • creating a whole new theme (too much work – overkill);

  • copying the template to the theme’s folder (not polite to the theme);

  • creating a child theme (overkill again);

  • putting the code in the functions.php file (not polite or good to edit a theme’s function.php file; better in a child theme, but that’s no good);

  • setting the pages meta to specify a template by name (but that requires a template in the theme’s folder);

  • or changing the template used by the Page (hence the question).

The code I used to do this is as follows. The template file I want to use is in the plugin’s templates folder. My plugin has previously created the “My Custom Page” page.

// include our template
add_filter( 'template_include', 'use_our_page_template', 99 );

function use_our_page_template( $template ) {

    if ( is_page( 'My Custom Page' )  ) {
        $new_template =  plugin_dir_path( __FILE__ ) . 'templates/mycustomtemplate.php';
        return $new_template;
    }
return;

The is_page() function can use the ID# of the page, or it’s title, or it’s slug (see docs). I use the page title as my parameter.

Note that if you edit the “My Custom Page”, you will not see the name of the template being used in the Template field of the editing screen. That doesn’t bother me, but could probably be fixed. Doesn’t matter; my template is used to output the page.

I put the above code in my plugin’s code. The filter is available as long as the plugin is enabled. Yeah, maybe a slight performance hit because the filter is enabled for the whole site, but acceptable to me. And I could probably change the page name to make it fully unique.

So, my solution solves the question: how to set a Page to use a template outside of the theme’s folder. The other answers, while containing some useful information, did not answer the original question.

And it works.

(Note: this question from 2010 pointed me to the ultimate solution.)

Leave a Comment