How to Create page on theme activation?

Sometimes your theme depends on certain pages to function properly and instead of relying on users to create those pages, it is always better to create them automatically as soon as the theme is activated.

Quick Tip : Programmatically Create a Category in WordPress

Here’s a sample code which allows you to create pages on theme activation,

if (isset($_GET['activated']) && is_admin()){
        $new_page_title = 'This is the page title';
        $new_page_content = 'This is the page content';
        $new_page_template = ''; //ex. template-custom.php. Leave blank if you don't want a custom page template.
        //don't change the code bellow, unless you know what you're doing
        $page_check = get_page_by_title($new_page_title);
        $new_page = array(
                'post_type' => 'page',
                'post_title' => $new_page_title,
                'post_content' => $new_page_content,
                'post_status' => 'publish',
                'post_author' => 1,
                $new_page_id = wp_insert_post($new_page);
                        update_post_meta($new_page_id, '_wp_page_template', $new_page_template);

Note : You need to put the following code in your functions.php file located inside your theme folder.


Leave a Comment.