5

I’d like to have a page added by default when a new site is created with WP Multisite.

So I have my function that creates two pages:

function my_default_pages() {
    $default_pages = array('Impress', 'Contact');
    $existing_pages = get_pages();

    foreach($existing_pages as $page) {
        $temp[] = $page->post_title;
    }

    $pages_to_create = array_diff($default_pages,$temp);

    foreach($pages_to_create as $new_page_title) {
        // Create post object
        $my_post = array();
        $my_post['post_title'] = $new_page_title;
        $my_post['post_content'] = 'This is my '.$new_page_title.' page.';
        $my_post['post_status'] = 'publish';
        $my_post['post_type'] = 'page';

        // Insert the post into the database
        $result = wp_insert_post( $my_post );
    }
}

And I found out that I have to hook into the wpmu_new_blog[1] action that fires when a new site is created.

add_action('wpmu_new_blog', 'my_default_pages');

But I don’t know how make both working together …

3
  • "But I don’t know how make both working together" - what do you mean? When/where are you calling the add_action? Nov 7, 2012 at 18:54
  • I call the add_action right after the function in my functions.php. But it doesn’t work. Nov 7, 2012 at 18:59
  • Where are you placing this code? Feb 19, 2014 at 14:57

1 Answer 1

11

The hook is not the problem - your code runs in the context of the current site, not the one just created! The following code isn't tested, but it should at least highlight the problem:

function wpse_71863_default_pages( $new_site ) {
    $default_pages = array(
        'Impress',
        'Contact',
    );
    
    switch_to_blog( $new_site->id );
    
    if ( $current_pages = get_pages() ) {
        $default_pages = array_diff( $default_pages, wp_list_pluck( $current_pages, 'post_title' ) );
    }

    foreach ( $default_pages as $page_title ) {        
        $data = array(
            'post_title'   => $page_title,
            'post_content' => "This is my $page_title page.",
            'post_status'  => 'publish',
            'post_type'    => 'page',
        );

        wp_insert_post( add_magic_quotes( $data ) );
    }
    
    restore_current_blog();
}

add_action( 'wp_insert_site', 'wpse_71863_default_pages' );
3
  • Ah, thanks—now I got it! Your code works perfectly! Nov 7, 2012 at 19:14
  • When the user registers the blog using frontendend registration form, $blog_id would hold new blog's id. But what particular context the code is running under? The main site (1) ?
    – Ejaz
    Sep 17, 2016 at 0:33
  • 1
    wpmu_new_blog is deprecated since WordPress 5.1 use wp_insert_site instead developer.wordpress.org/reference/hooks/wpmu_new_blog May 15, 2020 at 7:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.