In this tutorial, I’ll show you how to make your WordPress plugin automatically create a WordPress page when the plugin is activated from wp-admin.
Let’s just dive right in to the PHP code this time!
//Add Events page on activation:
$new_page_title = ‘Events’;
$new_page_content = ‘This is your page content that automatically gets inserted into the Events page!’;
$new_page_template = ”; //ex. template-custom.php. Leave blank if you don’t want a custom page template.
//don’t change the code below, unless you know what you’re doing
$page_check = get_page_by_title($new_page_title);
$new_page = array(
‘post_type’ => ‘page’,
‘post_title’ => $new_page_title,
‘post_content’ => $new_page_content,
‘post_status’ => ‘publish’,
‘post_author’ => 1,
$new_page_id = wp_insert_post($new_page);
update_post_meta($new_page_id, ‘_wp_page_template’, $new_page_template);
}//end install_events_pg function to add page to wp on plugin activation
That’s really all there is to it. Of course, you’ll want to edit the $new_pg_title to contain the title of your own custom page and you’ll want to edit $new_pg_content to contain html elements for your page content, but this will get you started. Just by copy and pasting the above code into your plugin’s main file, you will see the “Events” page added when you activate the plugin. If your plugin is already activated, simply deactivate and acti