WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm launching a new WordPress theme and was wondering if it's possible to select and activate that specific page's template in code rather than going into the CMS and manually selecting it from the drop-down. I ask because once I launch the theme, a whole bunch of pages won't have a template associated with them until I manually select it and I have traffic visiting my site already.

share|improve this question
What did you try so far? Please tell us your ideas and show us your research effort. Thanks. – kaiser Apr 2 '13 at 18:03

Presumably you are using wp_insert_post to create your pages. Having done so, do

update_post_meta($id, '_wp_page_template', 'my_template.php');
share|improve this answer

Option 1 (the best option):

If you have different page templates for each of the pages, you can name the templates with the format of "page-{slug}.php" and Wordpress will automatically pick those up, assuming a different page template is not already assigned.

For example: For an About page with the slug "about", your page template would be named page-about.php to assign that page automatically.

See the Page section of the Wordpress Template Hierarchy for full details.

Option 2 (an okay option if you have database access):

If you are going to use a specific page template for several pages or can't match the slugs to the file names for some reason you'll have to do a little bit more work.

If you have database access, you can run SQL to update them. For example, write a line like this for each page, replacing the post_id and meta_value as appropriate:

UPDATE wp_postmeta SET meta_value = 'new-template.php' WHERE meta_key = '_wp_page_template' AND post_id = 1234;

You can also remove all the existing page template assignments with this SQL:

DELETE * FROM wp_postmeta WHERE meta_key = '_wp_page_template';

Of course, make sure you back up your site and database before proceeding.

share|improve this answer
It's always better to use the tools WP gives you (update_post_meta) rather than directly manipulating the DB. – vancoder Apr 2 '13 at 19:24
Agreed, which is why that is the secondary option. It sounds like Matt is apply a new theme to an existing site. This is an alternative that can be done quickly with a DB script during such a migration. – ksemel Apr 3 '13 at 14:23

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.