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 …
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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' );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0