Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
2  
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
add comment

2 Answers

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
add comment

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
1  
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
add comment

Your Answer

 
discard

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.