First of all you should use register_activation_hook
, this hook runs when a wordpress plugin is installed.
I would also replace the call to the $wpdb
for inserting post with wp_insert_post
.
wp_insert_post
returns the post ID on success and this can be used to update the option for both page_on_front
and show_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' );