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 know the page template is set in the wpdb as meta_key = _wp_page_template and meta_value = template.php.

How can I write a SQL script to set each post where post_type = 'page' to a specific template?

EDIT: Based on the comments below, I'll add the detail that I am wishing to "normalize" my pages since some are set to custom templates.

share|improve this question
4  
Why is this necessary? Can't you just edit page.php? –  kramdraw85 Jan 25 '12 at 19:08
    
I agree with kramdraw85, why change a value for ALL PAGES when by default they already use the same template file - page.php –  Shane Jan 25 '12 at 20:02
    
@kramdraw85 please post that response as an answer, so we can up-vote it. –  Chip Bennett Jan 25 '12 at 20:05

1 Answer 1

up vote 3 down vote accepted

EDIT As noted in the comments on your question, the best approach would just be to edit your page.php file. If you want ALL of your pages to have the same page template, and not have to do anything extra to set it that way, it's quite obvious why this is a good idea. :)

Then, you can make a custom page template for the pages that you don't use your default page template for. That is pretty much what that system was made for!


If you insist though:

The page template of each page is actually stored as a custom field, you could loop over each post in your code and set the page template that way, instead of going and doing it in the database manually. See below:

add_action( 'admin_init', 'set_page_templates' );

function set_page_templates(){

    foreach( get_posts('post_type=page') as $page ) {
        $current_template = get_post_meta( $page->ID, '_wp_page_template', true );
        $new_template = 'new_template.php';

        if( $current_template != $new_template )
            update_post_meta( $page->ID, '_wp_page_template', $new_template );
    }

}

There may be a better action to put this on, as this will run on every admin page load. Maybe you could run this once and then remove the code, it should work fine that way. Alternatively, you could hook it onto the save_post action (which actually will return the page ID you are saving for you as one of your function arguments) to automatically change the page template if it isn't what you want it to be on save of a post or page (of course skipping the foreach in that case).

share|improve this answer

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.