How to create a page and assign a page template automatically in WordPress

Sometime your theme depends on a few special pages, and it’s better to create them automatically after theme activation. You could also ask your users to create these pages and assign a few specific page template, but why would you do that if there is a scope of doing it automatically from your theme. Here is a simple snippet to take care of that 🙂

Step 1: Create a page template in your theme (say awesome-page.php) which has the following code
[sourcecode language=”php”]
<?php
/**
* Template Name: Awesome Page
*/
[/sourcecode]

Step 2: Add the following code in your theme’s functions.php file 🙂

[sourcecode language=”php”]
add_action(‘after_setup_theme’, ‘create_pages’);
function create_pages(){
$awesome_page_id = get_option("awesome_page_id");
if (!$awesome_page_id) {
//create a new page and automatically assign the page template
$post1 = array(
‘post_title’ => "Awesome Page!",
‘post_content’ => "",
‘post_status’ => "publish",
‘post_type’ => ‘page’,
);
$postID = wp_insert_post($post1, $error);
update_post_meta($postID, "_wp_page_template", "awesome-page.php");
update_option("awesome_page_id", $postID);
}
}
[/sourcecode]

And you are done!