Software, Development, and WordPress

Programmatically Set a WordPress Template

If you're an advanced developer or just want the TL;DR version of this, skip to the code.

Programmatically Add a Template to a Page

One of the nicest things about WordPress is the ability to customize the look and feel of pages by applying customized page templates.

Whenever I am working on an advanced theme or an application, I often treat my pages like views and my templates like layouts.

In cases like this, I often need to programmatically create posts, pages, and other data upon theme activation. Similarly, I’ve also needed to programmatically add a template to a page during activation, as well.

This is relatively easy to do.

Get The Page

Technically, all you need in order to programmatically add a template to a page is the page ID. Given the fact that I’ve already shared how to create a page, it’ll be easier (and shorter!) to share how to get the ID of a page by its title.

It’s relatively common to have a sitemap template and it’s a best practice to name the corresponding page “Sitemap.” So, assuming that you have a page called “sitemap,” you can get easily get a reference to the page’s corresponding object by using get_page_by_title.

// Attempt to load the page by its title
$page = get_page_by_title( 'Sitemap', OBJECT, 'page' );

// If the page is null, set the ID to -1; otherwise, use the page's ID
$page_id = null == $page ? -1 : $page->ID;

Note that if the page isn’t returned, then I’m setting the $page_ID to -1.

In cases like this, I often use negative values to keep track of if variables have been properly set – this makes it much easier to program defensively and perform error logging that blindly assuming values are initialized.

This will also play a role in the context of the full function.

Update The Post Meta

It’s easy to add a template to a page once you have the page’s ID. Assuming that you have the page template properly formatted, it’s a matter of updating the post meta.

Generally speaking, post meta data is just that – it’s data that’s associated with any given post type (be it pages, posts, or any custom post type). Post meta is associated with a post by using a post’s ID, a key value (in this case, this is page template key), and a value for the key. In this case, it’s the template file.

WordPress stores a page’s template in the associated page’s post meta. This is done programmatically by using update_post_meta.

// Only set the template if it's a valid page
if( -1 != $page_id ) {
  update_post_meta( $page_id, '_wp_page_template', 'template-sitemap.php' );
} // end if

Note that the ‘_wp_page_template’ key is the key that WordPress natively uses to associate a template to a page and ‘template-sitemap.php’ is the name of the template in the project.

Obviously, this can be generalized to set any given template.

Programmatically Set a WordPress Template

This is the TL;DR version of all of the code covered in this article. It’s meant for those that want to see everything tied together or those that skipped the rest of the article.

The main difference in the function that’s below and the code that’s above is that I’ve generalized the code to accept the name of any page and the name of any template. I’ve commented the code to make this as clear as possible.

 * Attaches the specified template to the page identified by the specified name.
 * @params    $page_name        The name of the page to attach the template.
 * @params    $template_path    The template's filename (assumes .php' is specified)
 * @returns   -1 if the page does not exist; otherwise, the ID of the page.
function attach_template_to_page( $page_name, $template_file_name ) {

    // Look for the page by the specified title. Set the ID to -1 if it doesn't exist.
    // Otherwise, set it to the page's ID.
    $page = get_page_by_title( $page_name, OBJECT, 'page' );
    $page_id = null == $page ? -1 : $page->ID;

    // Only attach the template if the page exists
    if( -1 != $page_id ) {
        update_post_meta( $page_id, '_wp_page_template', $template_file_name );
    } // end if

    return $page_id;

} // end attach_template_to_page

To add a template to a page, you’d now do the following:

attach_template_to_page( 'sitemap', 'template-sitemap.php' );

Of course, you  may also want to wrap this into a conditional verifying that -1 isn’t returned, but that’s ultimately your call.

Resources In The Codex

For reference, here are the Codex articles related to some of the functions that I used above:


  1. Jake

    I assume this only works if the template you are setting is in the /wp-content/themes/your-theme/ directory? I’ve been looking for a way to set a page template that exists inside the plugins directory.

    • Tom McFarlin

      That is correct, but there are some alternatives.

      First, check out this post but be sure to read the comments. It’s not a perfect solution – more of a proof of concept.

      Secondly, you may be able to register a template by taking advanced of the `plugins_url` function and set that as the meta data, though I’ve never personally tried it so I can’t vouch for it.

  2. Gary Cook

    although post_meta is for posts the example is for a page template. is it even possible to have a page template? or only the post formats, like asides? please.

    • Tom McFarlin

      Do you mean is it even possible to have a post template? Let me know – we’ll see if we can clear it up :).

  3. Nader

    This is already pretty helpful, thanks!

    I am wondering if there is also a way to get rid of using pages alltogether.
    Say I want my plugin to provide a url(structure) that, if it gets hit, loops through some custom post types. Would I still need to create a page, then embed a template with php code, or, is there another way?

    Maybe you can point me in the right direction.


    • Tom

      I am wondering if there is also a way to get rid of using pages alltogether.
      Say I want my plugin to provide a url(structure) that, if it gets hit, loops through some custom post types. Would I still need to create a page, then embed a template with php code, or, is there another way?

      Do you mean pages in terms of a post type displaying in the admin bar, or are you looking to totally rid WordPress of pages and simply define templates of your own that render information?

      If it’s the former, then you can get rid of the menu item (as it’s just a post type itself, really), but if it’s the latter, then you’ll have to do a bit more work because you’ll need to hook into The Loop, pull out data from the database for the corresponding post (since that’s what everything is in WordPress), and then move forward from there.

      Another option would be to programmatically create the pages and apply the templates on, say, theme activation or plugin activation, but there’s also a lot of code and checking that would need to go into building something like that.

      Regardless, it is possible, but I wouldn’t really recommend it. I sounds as if you’re trying to circumvent native functionality but replace it with something that basically does what’s already being done.

      Then again, I’m likely misunderstanding the comment. I do that, you know ;).

  4. Eugen Mihailescu

    There are situations when it’s counter-productive to relay on what is stored in database (post-meta).

    For instance I have posts that have certain properties and I want dinamically to set the page template without messing with the database content (I like it as is :-).

    For those situation a filter hook will do the job too:


    add_filter( “page_template”, “plugin_function_name” );

    function plugin_function_name(){

    // use a custom template only when needed
    if ('my-slug' == basename ( get_permalink () )){
    return get_template_directory () . '/my-template.php';


    • Tom

      Sure, sure. There’s rarely a one-size fits all solution, but when you say that you’re looking to work with the “properties”, what specifically are you talking about?

      Also, why would you rather use a filter to apply a template at runtime rather than store the value in the database so it’s set once rather than read via the hook?

Leave a Reply

© 2020 Tom McFarlin

Theme by Anders NorenUp ↑