Adaptive Web

A web development blog

Creating pages automatically on plugin activation in WordPress

If you are creating a WordPress plugin, often times you will need to reference a specific page in order to display some kind of data or other information. Although it is possible to manually create pages in WordPress, required by a plugin, creating pages automatically on plugin activation will ensure your plugin works out of the box.

The first step is to register a function in your plugin that will fire upon activation. The following code uses the register_activation_hook function. The function accepts two parameters $file and $function. $file is a string representing the path to the main plugin file; $function is a reference to the function that will contain our activation code.

register_activation_hook( $file, $function );

The first line uses a constant to store the path to the main plugin file. This will usually be a file in the plugin root directory with the same name as the plugin folder. Next we use the register_activation_hook function to register our activation function, referencing the path to the plugin file.

The first thing we do on activation is check that the current user is allowed to activate plugins. We do this using the current_user_can function. The first and only required parameter accepts a string representing a role or capability that you would like to check that the current user has. A detailed list of roles and their associated capabilities can be found here.

register_activation_hook( __FILE__, 'beardbot_plugin_activation' );
function beardbot_plugin_activation() {
  if ( ! current_user_can( 'activate_plugins' ) ) return;
}

Finally, we create our new page, after we check that a page with the same name does not exist.

register_activation_hook( __FILE__, 'beardbot_plugin_activation' );
function beardbot_plugin_activation() {
  
  if ( ! current_user_can( 'activate_plugins' ) ) return;
  
  global $wpdb;
  
  if ( null === $wpdb->get_row( "SELECT post_name FROM {$wpdb->prefix}posts WHERE post_name = 'new-page-slug'", 'ARRAY_A' ) ) {
     
    $current_user = wp_get_current_user();
    
    // create post object
    $page = array(
      'post_title'  => __( 'New Page' ),
      'post_status' => 'publish',
      'post_author' => $current_user->ID,
      'post_type'   => 'page',
    );
    
    // insert the post into the database
    wp_insert_post( $page );
  }
}

Here is a full list of parameters accepted by the wp_insert_post function.

Creating pages automatically on plugin activation in WordPress is the best way to ensure maximum compatibility with any WordPress website.

References