wp_insert_post()
返回新帖子的帖子ID。您可以使用该ID设置父帖子。
实例
$about_id = wp_insert_post(
array (
\'post_title\' => \'About\',
\'post_status\' => \'publish\',
\'post_type\' => \'page\',
)
);
wp_insert_post(
array (
\'post_title\' => \'Information\',
\'post_status\' => \'publish\',
\'post_type\' => \'page\',
\'post_parent\' => $about_id,
)
);
在您的情况下,我将重新构造页面数据并构建嵌套数组:
$default_pages = array(
\'Contact\' => array(
"content" => "This is your \'Contact\' page. Enter in your content here."
),
\'About\' => array(
"content" => "This is your \'About\' page. Enter in your content here.",
"children" => array(
\'Information\' => array(
"content" => "This is your \'Information\' page. Enter in your content here."
)
),
),
\'Home\' => array(
"content" => "This is your \'Home\' page. Enter in your content here."
),
);
然后,我将页面插入移动到一个单独的函数,以允许递归:
function insert_page( $title, Array $properties, $post_parent = 0 )
{
$data = array(
\'post_title\' => $title,
\'post_content\' => $properties[ "content" ],
\'post_status\' => \'publish\',
\'post_type\' => \'page\',
\'post_parent\' => $post_parent,
);
$id = wp_insert_post( add_magic_quotes( $data ) );
if ( ! empty ( $properties[ "children" ] ) )
{
foreach ( $properties[ "children" ] as $child_title => $child_properties )
insert_page( $child_title, $child_properties, $id );
}
}
因此,您的完整代码应该如下所示:
function default_pages( $blog_id )
{
$default_pages = array(
\'Contact\' => array(
"content" => "This is your \'Contact\' page. Enter in your content here."
),
\'About\' => array(
"content" => "This is your \'About\' page. Enter in your content here.",
"children" => array(
\'Information\' => array(
"content" => "This is your \'Information\' page. Enter in your content here."
)
),
),
\'Home\' => array(
"content" => "This is your \'Home\' page. Enter in your content here."
),
);
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 => $properties )
insert_page( $page_title, $properties );
restore_current_blog();
}
function insert_page( $title, Array $properties, $post_parent = 0 )
{
$data = array(
\'post_title\' => $title,
\'post_content\' => $properties[ "content" ],
\'post_status\' => \'publish\',
\'post_type\' => \'page\',
\'post_parent\' => $post_parent,
);
$id = wp_insert_post( add_magic_quotes( $data ) );
if ( ! empty ( $properties[ "children" ] ) )
{
foreach ( $properties[ "children" ] as $child_title => $child_properties )
insert_page( $child_title, $child_properties, $id );
}
}