从wp_insert_post()
documentation, 这个page_template
参数如下所示:
page\\u template:如果post\\u type为“page”,将尝试设置页面模板。失败时,函数将返回WP\\u错误或0,并在调用最终操作之前停止。如果post\\u类型不是“page”,则忽略该参数。您可以通过使用键“\\u wp\\u page\\u template”调用update\\u post\\u meta()为非页面设置页面模板。
因此,您需要使用插入页面wp_insert_post()
并使用page_template
参数:
add_action( \'admin_init\', \'mytheme_admin_init\' );
function mytheme_admin_init() {
if ( ! get_option( \'mytheme_installed\' ) ) {
$new_page_id = wp_insert_post( array(
\'post_title\' => \'Blog\',
\'post_type\' => \'page\',
\'post_name\' => \'blog\',
\'comment_status\' => \'closed\',
\'ping_status\' => \'closed\',
\'post_content\' => \'\',
\'post_status\' => \'publish\',
\'post_author\' => get_user_by( \'id\', 1 )->user_id,
\'menu_order\' => 0,
// Assign page template
\'page_template\' => \'template-blog.php\'
) );
update_option( \'mytheme_installed\', true );
}
}
或者,如果要为其他帖子类型设置“页面模板”:
add_action( \'admin_init\', \'mytheme_admin_init\' );
function mytheme_admin_init() {
if ( ! get_option( \'mytheme_installed\' ) ) {
$new_page_id = wp_insert_post( array(
\'post_title\' => \'Blog\',
\'post_type\' => \'my_custom_post_type\',
\'post_name\' => \'blog\',
\'comment_status\' => \'closed\',
\'ping_status\' => \'closed\',
\'post_content\' => \'\',
\'post_status\' => \'publish\',
\'post_author\' => get_user_by( \'id\', 1 )->user_id,
\'menu_order\' => 0
) );
if ( $new_page_id && ! is_wp_error( $new_page_id ) ){
update_post_meta( $new_page_id, \'_wp_page_template\', \'template-blog.php\' );
}
update_option( \'mytheme_installed\', true );
}
}