WP MultiSite:默认添加关于博客创建的页面

时间:2012-11-07 作者:user1706680

我希望在使用WP Multisite创建新站点时,在默认情况下添加一个页面。

因此,我有一个创建两个页面的函数:

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 );
    }
}
我发现我必须wpmu_new_blog[1] 创建新站点时激发的操作。

add_action(\'wpmu_new_blog\', \'my_default_pages\');
但我不知道如何让两个人一起工作…

1 个回复
最合适的回答,由SO网友:TheDeadMedic 整理而成

钩子不是问题所在-您的代码在当前站点的上下文中运行,而不是在刚刚创建的上下文中运行!以下代码未经测试,但至少应突出显示问题:

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\' );

结束