Useful: Set templates for all WordPress pages programatically

Come across this little snippet while I’m searching for a solution to change all page templates from default to a custom one. I didn’t want to change the default template in general either change the page template itself – but only change the template setting for all pages yet created.

This solutions rewrites all post meta entries in the database with the value¬† ‘_wp_page_template’ if they differ from my desired setting.

add_action( 'admin_init', 'set_page_templates' );

function set_page_templates(){

    foreach( get_posts('post_type=page&posts_per_page=-1') as $page ) {
        $current_template = get_post_meta( $page->ID, '_wp_page_template', true );
        $new_template = 'home-panels.php'; // Change home-panels.php to your template file name

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

Put this in yout theme’s functions.php, reload the backend and remove this code afterwards.

Found here:

https://wordpress.stackexchange.com/questions/40161/set-page-template-for-all-pages

By the way:

Changing the preselected entry in the metabox ist easy also, so every newly created page will get this as template:

function set_default_page_template() {
    global $post;
    if ( 'page' == $post->post_type
        && 0 != count( get_page_templates( $post ) )
        && get_option( 'page_for_posts' ) != $post->ID // Not the page for listing posts
        && '' == $post->page_template // Only when page_template is not set
    ) {
        $post->page_template = "home-panels.php"; // Change home-panels.php to your template file name
    }
}
add_action('add_meta_boxes', 'set_default_page_template', 1);

Put this in your theme’s functions.php, that’s all. Don’t know, where I found this but it’s useful also.