Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 …

share|improve this question
    
"But I don’t know how make both working together" - what do you mean? When/where are you calling the add_action? –  TheDeadMedic Nov 7 '12 at 18:54
    
I call the add_action right after the function in my functions.php. But it doesn’t work. –  user1706680 Nov 7 '12 at 18:59
    
Where are you placing this code? –  1.21 gigawatts Feb 19 at 14:57

1 Answer 1

up vote 3 down vote accepted

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( $blog_id )
{
    $default_pages = array(
        'Impress',
        'Contact',
    );

    switch_to_blog( $blog_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( 'wpmu_new_blog', 'wpse_71863_default_pages' );
share|improve this answer
    
Ah, thanks—now I got it! Your code works perfectly! –  user1706680 Nov 7 '12 at 19:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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