howto idea PHP wordpress

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”]
* Template Name: Awesome Page

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);

And you are done!

10 replies on “How to create a page and assign a page template automatically in WordPress”

Thats pretty cool !!! Hasin vai, is it possible to Put specific Data in those page? Like most of the time clients ask for Terms of Condition page or DMCA kinda page. I was thinking about writing a simple plugin for it. There are already plugin for that job, but to heavy. So If i put any data in ‘post_content’ => “MY DATA”, is that have to formatted as HTML or plain text?

Thanks Sir,,, But,, Sir.. I just finished Primary level of PHP and mysql .. Those code you write above .. That is good.. But I don’t know where and how to implement it in wordpress… Because I didn’t Work with it by PHP. I just know how to crate a blog in wordpress and simple knowledge of theme customization… Hope Your tutorial about wordpress help me … Thanks.. —

Leave a Reply

Your email address will not be published. Required fields are marked *