安装时,自动创建页面并将其设置为首页

时间:2017-01-07 作者:apasajja

安装时,我希望自动创建一个页面并将其设置为首页。我可以创建页面,但无法将其设置为首页。

下面是WP Install Defaults 安装后自动创建页面的代码:

function wp_install_defaults( $user_id ) {
    global $wpdb, $wp_rewrite, $table_prefix;

    $now = current_time( \'mysql\' );
    $now_gmt = current_time( \'mysql\', 1 );

    // First Page
    $first_page = sprintf( __( "This is an example page.
        Have fun!" ), admin_url() );
    $wpdb->insert( $wpdb->posts, array(
        \'post_author\' => $user_id,
        \'post_date\' => $now,
        \'post_date_gmt\' => $now_gmt,
        \'post_content\' => $first_page,
        \'comment_status\' => \'closed\',
        \'post_title\' => __( \'Sample Page\' ),
        \'post_name\' => __( \'sample-page\' ),
        \'post_modified\' => $now,
        \'post_modified_gmt\' => $now_gmt,
        \'post_type\' => \'page\',
    ));
    $wpdb->insert( $wpdb->postmeta, array( \'post_id\' => 2, \'meta_key\' => \'_wp_page_template\', \'meta_value\' => \'default\' ) );
}
我被困在这里,我不知道如何将页面设置为头版。

下面的代码取自2017年的主题,我不知道如何将其移植到WP Install Defaults

add_theme_support( \'starter-content\', array(
        // ...
        \'options\' => array(
            \'show_on_front\' => \'page\',
            \'page_on_front\' => \'{{sample-page}}\',
        ),
    // ...
 );

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

首先,你应该使用register_activation_hook, 当安装了wordpress插件时,这个钩子就会运行。

我也会把电话换成$wpdb 用于插入带有wp_insert_post.

wp_insert_post 成功时返回帖子ID,这可用于更新两者的选项page_on_frontshow_on_front.

function wp_install_defaults( $user_id ) {

    $now = current_time( \'mysql\' );
    $now_gmt = current_time( \'mysql\', 1 );

    // First Page
    $first_page = sprintf( __( "This is an example page.
        Have fun!" ), admin_url() );
    $query = new WP_Query( array( 
        \'pagename\' => \'sample-page\'
    ) );
    if ( ! $query->have_posts() ) {
        // Add the page using the data from the array above
        $post_id = wp_insert_post(
            array(
                \'post_author\' => $user_id,
                \'post_date\' => $now,
                \'post_date_gmt\' => $now_gmt,
                \'post_content\' => $first_page,
                \'comment_status\' => \'closed\',
                \'post_title\' => __( \'Sample Page\' ),
                \'post_name\' => __( \'sample-page\' ),
                \'post_modified\' => $now,
                \'post_modified_gmt\' => $now_gmt,
                \'post_type\' => \'page\',
            )
        );

        if ( $post_id )
        {
            update_option( \'page_on_front\', $post_id );
            update_option( \'show_on_front\', \'page\' );
        }
    }
}
register_activation_hook( __FILE__, \'wp_install_defaults\' );

相关推荐

Custom WordPress Installation

我想知道下面的帖子中描述的自定义WordPress安装的方法是否有更新版本。http://wpbits.wordpress.com/2007/08/10/automating-wordpress-customizations-the-installphp-way/