I’m creating a plugin that will need to add a new WP page upon activation and then I want it to remove that same page upon uninstallation. Do I have to manually store that page id in the DB somewhere or is there a native WP option to remember that automatically?
My code so far:
register_activation_hook(__FILE__, 'create_page');
register_uninstall_hook(__FILE__, 'remove_page');
function create_page() {
global $user_ID;
$page['post_type'] = 'page';
$page['post_content'] = 'Page content will go here.';
$page['post_parent'] = 0;
$page['post_author'] = $user_ID;
$page['post_status'] = 'publish';
$page['post_title'] = 'Page Title';
$pageid = wp_insert_post ($page);
if ($pageid == 0) {
echo "Something went wrong. Could not successfully add a new page.";
}
}
Why do you need to create a page?
Its possible that before plugin deactivation, the page no longer exists, so your deletion function will need to check for if it exists
But yes you will need to store the ID somewhere.
Best option is to just update_option(‘icreatedapage’, $pageid);
Tho what do you do if you page fails to create?
You will need to considering including instructions on how to manually create it, or let the user do it themselves…
Just for reference:
A file called uninstall.php will be run automagically when the plugin is deactivated.