How to create a page when a theme is activated?

I want my theme to have an ‘about’ page available by default when a user uses my theme.

Is there a way to auto create a page when a user selects your template?

Or some other way of achieving this?

4 Answers
4

There is a hook specifically for this purpose, called after_switch_theme. You can hook into it and create your personal page after theme activation. Have a look at this:

add_action( 'after_switch_theme', 'create_page_on_theme_activation' );

function create_page_on_theme_activation(){

    // Set the title, template, etc
    $new_page_title     = __('About Us','text-domain'); // Page's title
    $new_page_content="";                           // Content goes here
    $new_page_template="page-custom-page.php";       // The template to use for the page
    $page_check = get_page_by_title($new_page_title);   // Check if the page already exists
    // Store the above data in an array
    $new_page = array(
            'post_type'     => 'page', 
            'post_title'    => $new_page_title,
            'post_content'  => $new_page_content,
            'post_status'   => 'publish',
            'post_author'   => 1,
            'post_name'     => 'about-us'
    );
    // If the page doesn't already exist, create it
    if(!isset($page_check->ID)){
        $new_page_id = wp_insert_post($new_page);
        if(!empty($new_page_template)){
            update_post_meta($new_page_id, '_wp_page_template', $new_page_template);
        }
    }
}

I suggest you use a unique slug to make sure the code always functions properly, since pages with slugs like about-us are very common, and might already exist but don’t belong to your theme.

Leave a Comment