Today we will learn How to create page and assign a page template automatically in WordPress

Sometimes 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 sometimes it is not much feasible to ask users to create page on their own and assign templates of their choice.
Because If you are creating a new theme either for sale or for a client you may want to have it create a custom page or pages when the theme is activated.

Also, 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  page template in your theme (say movietemplate-page.php) which has the following code


 * Template Name: Movie Page

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

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' => "Movie Page!",
	            'post_content' => "",
	            'post_status' => "publish",
	            'post_type' => 'page',
	        $postID = wp_insert_post($post1, $error);
	        update_post_meta($postID, "_wp_page_template", "movie-page.php");
	        update_option("awesome_page_id", $postID);

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.