WordPress uninstall.php file – The Complete Guide

WordPress uninstall.php file – The Complete Guide

All

WordPress / All 44 Views comments

WordPress plugins that clear up after themselves are pure superior sauce. In case you are creating a plugin that provides any kind of knowledge to the WordPress database, it is vital that the plugin removes any undesirable or unused knowledge if and when the plugin ever is uninstalled. This whole information explains helpful methods for doing this utilizing the highly effective and useful uninstall.php file.

A easy but full information to uninstall.php, with a TON of helpful uninstall methods!

Contents

How uninstall.php works

Principally you add a file named uninstall.php to the plugin's primary (root) listing. For instance, say we've a plugin named "Add Knowledge to WP Database", and the primary listing is /add-data-wp-database/. Inside that listing, we will add uninstall.php like so:

/add-data-wp-database/
        /add-data-wp-database.php
        /index.php
        /uninstall.php <--- right here it's.
        /readme.txt

Now every time the plugin is uninstalled (eliminated) by way of the "Plugins" display within the Admin Space (see thumbnail at starting of this publish), WordPress will discover and execute uninstall.php. This makes it attainable for plugin builders to "clear up" any undesirable or unused knowledge from the database.

That is the way it works in a nutshell. For extra particulars, take a look at the WP Codex.

What's inside uninstall.php

The uninstall.php file might embrace any code that's essential to deal with correct clear up and uninstall routines for the plugin. On the very least, some code ought to be included that protects the file from undesirable entry. Right here is an easy, really helpful strategy to do it:

<?php // exit if uninstall fixed is just not outlined
if (!outlined('WP_UNINSTALL_PLUGIN')) exit;

These strains (or one thing comparable) must be situated at first of uninstall.php, earlier than another code. This code works by checking for the WP_UNINSTALL_PLUGIN fixed, which is outlined by WordPress simply previous to loading uninstall.php. So if something aside from WordPress tries to entry the file, the script will exit instantly.

To provide you a greater concept, right here is an instance uninstall.php file that removes a number of forms of knowledge. Observe that a lot of the code is excluded for readability.

<?php // exit if uninstall fixed isn't outlined
if (!outlined('WP_UNINSTALL_PLUGIN')) exit;

// take away plugin choices

// take away plugin transients

// take away plugin cron occasions

// ..and so forth., based mostly on what must be eliminated

So the precise code methods which are added to the uninstall file rely upon the info that wants eliminated or modified. They'll differ from plugin to plugin, so you will have to know precisely which knowledge want eliminated earlier than including the suitable method. Within the subsequent sections of this tutorial, you will discover methods for eradicating all types of knowledge from the WordPress database.

Necessary: Solely add the methods which are crucial. You need to be very exact, as defined on this word to the wise.

Delete plugin choices

In all probability the most typical uninstall method is to delete plugin choices utilizing the WordPress perform delete_option(). For instance, to take away an choice named myplugin_options, add this code to uninstall.php:

// delete plugin choices
delete_option('myplugin_options');

Or when you have a number of choices to delete, you'll be able to loop by means of an array:

// delete a number of choices
$choices = array(
        'myplugin_option_1',
        'myplugin_option_2',
        'myplugin_option_3',
);
foreach ($choices as $choice) 
        if (get_option($choice)) delete_option($choice);

To make use of this code, rename the array gadgets (e.g., myplugin_option_1 et al) with the names of the plugin choices that you simply need to take away. Straightforward peasy.

Professional Tip: If utilizing plugin choices for another uninstall method, do NOT delete the choices till after you're completed utilizing them.

Delete plugin transients

One other widespread method is to take away any plugin transients from the database. To take action, we will use the delete_transient() perform:

// delete plugin transient
delete_transient('myplugin_transient');

Or when you have a number of transients to delete, you possibly can loop via an array:

// delete a number of transients
$transients = array(
        'myplugin_transient_1',
        'myplugin_transient_2',
        'myplugin_transient_3',
);
foreach ($transients as $transient) 
        delete_transient($transient);

To make use of this code, rename the array gadgets (e.g., myplugin_transient_1 et al) with the names of the plugin transients that you simply need to take away.

Delete cron occasions

The subsequent method exhibits find out how to delete cron occasions utilizing the WordPress perform, wp_unschedule_event(). Right here is an instance:

// delete cron occasion
$timestamp = wp_next_scheduled('myplugin_cron_event');
wp_unschedule_event($timestamp, 'myplugin_cron_event');

The trick right here is to make use of wp_next_scheduled() to get the right $timestamp worth for the transient that you simply need to delete.

Delete database tables

Right here is one in every of my favorites. You must be very cautious with this system. Make absolute sure that the desk identify is right. With that in thoughts, right here is an instance that exhibits learn how to delete a desk named myplugin_table:

// delete database desk
international $wpdb;
$table_name = $wpdb->prefix .'myplugin_table';
$wpdb->question("DROP TABLE IF EXISTS $table_name");

This system makes use of the wpdb class to outline the $table_name after which drop (delete) the desk if it exists. Once more, it is rather essential that you simply substitute myplugin_table with the right identify of the desk that you simply need to take away. No different modifications to the code are required. Keep in mind to check completely!

Delete posts and pages

To delete WP Posts and Pages, we will use wp_trash_post(). For instance, to delete the publish with ID equal to 44:

// delete submit id 44
wp_trash_post(44);

So the trick with this system is figuring out the right submit or web page ID(s). There are a number of methods to do that; in all probability easiest method is to report the ID of any posts or pages which are added by your plugin. So for instance, in case your plugin provides three pages when it's first activated, you can add these web page IDs to the database as an choice. That means you possibly can examine the choices to get the right posts to be deleted. In code, which may look one thing like this:

// delete pages
$myplugin_pages = get_option('myplugin_pages');
if (is_array($myplugin_pages) && !empty($myplugin_pages)) 
        foreach ($myplugin_pages as $myplugin_page) 
                wp_trash_post($myplugin_page);
        

Right here we use get_option() to seize our array of web page IDs. Then we loop by means of the array and use wp_trash_post() to delete every of them. Word that this similar method can be utilized to delete any publish or submit sort, not simply restricted to pages.

Necessary: Solely delete posts and pages in case you are completely positive that the consumer doesn't need them. One strategy to deal with that is so as to add an choice within the plugin settings, the place you ask the consumer if the no matter posts and/or pages ought to be deleted when the plugin is uninstalled. Extra about this here.

Delete Customized Submit Sort posts

Right here we're speaking about deleting posts which are outlined as a sure Customized Submit Sort (CPT). So we're not deleting the publish sort per se, slightly all posts that belong to the publish sort. To do that, we will use the wp_delete_post() perform. Right here is an instance that exhibits how one can delete all posts that belong to the customized submit sort named myplugin_cpt.

// delete customized publish sort posts
$myplugin_cpt_args = array('post_type' => 'myplugin_cpt', 'posts_per_page' => -1);
$myplugin_cpt_posts = get_posts($myplugin_cpt_args);
foreach ($myplugin_cpt_posts as $submit) 
        wp_delete_post($post->ID, false);

Right here we use get_posts() to get all posts that belong to the myplugin_cpt customized publish sort. We then loop by way of the outcomes and use wp_delete_post() to delete every CPT submit. The one factor that you'll want to change on this code is the identify (slug) of the customized submit sort, myplugin_cpt. And reminder, be sure that the consumer truly needs to have all of their CPT posts deleted, perhaps by including a plugin choice that asks them. Do not simply assume, particularly when submit content material is worried.

Observe: The above method makes use of wp_delete_post() to delete CPT posts. Perceive that this perform additionally deletes all the things that's tied to the posts, together with feedback, submit meta fields, phrases, and extra.

Notice: The second parameter of the wp_delete_post() perform presently is about to false. That tells WordPress to ship the publish to the Trash, the place the consumer can delete it (or restore it) later. In case you would moderately pressure delete the submit utterly, change the parameter to true.

Delete consumer meta

To delete consumer metadata, we will use the delete_user_meta() perform. For instance, if we need to delete all consumer meta knowledge named myplugin_user_meta, we will do that:

// delete consumer meta
$customers = get_users();
foreach ($customers as $consumer) 
        delete_user_meta($user->ID, 'myplugin_user_meta');

Right here we use get_users() to get an array of all customers. Then we loop via the array and use delete_user_meta to delete all consumer meta knowledge named myplugin_user_meta. Thus, to make use of this code method, exchange the myplugin_user_meta with the identify of the metadata that you simply need to delete.

Notice: As written, the above method removes meta from all customers. If for some cause you want to choose solely a subset of customers, you are able to do so by passing an array of arguments to get_users(). For extra info, take a look at WP_User_Query::prepare_query() within the WordPress documentation.

Delete publish meta

In case your plugin provides any publish metadata, you'll be able to take away it utilizing delete_post_meta(). Right here is an instance displaying methods to take away all publish meta named myplugin_post_meta.

// delete publish meta
$myplugin_post_args = array('posts_per_page' => -1);
$myplugin_posts = get_posts($myplugin_post_args);
foreach ($myplugin_posts as $publish) 
        delete_post_meta($post->ID, 'myplugin_post_meta');

This system makes use of get_posts() to get all posts (see observe under). Then it loops by way of the posts and deletes all meta named myplugin_post_meta. So to make use of this system, substitute myplugin_post_meta with the identify of the submit meta knowledge that you simply need to delete. Bada bing, bada growth.

Notice: To get all posts utilizing get_posts(), set the posts_per_page parameter to -1, as proven within the above instance.

Restrict take away meta to CPT

Yet one more tip for eradicating publish meta. If you wish to take away meta from solely a selected publish sort (CPT), substitute the worth of $myplugin_post_args within the above code to the next:

array('post_type' => 'myplugin_cpt', 'posts_per_page' => -1);

Right here we add the post_type parameter for get_posts(). To make use of on your personal publish sort, exchange myplugin_cpt with the CPT that you simply need to choose.

Alternate technique utilizing delete_metadata()

An alternate, equal option to take away all meta is to make use of the delete_metadata() perform. The great factor about this perform is that it may be used to delete all meta for any remark, submit, time period, or consumer. Right here is an instance the place we delete all submit meta named myplugin_meta_key:

// delete submit meta
delete_metadata('submit', zero, 'myplugin_meta_key', '', true);

This system is all about parameters. There are 5 of them, so as:

  • $meta_type — Object sort (remark, publish, time period, or consumer)
  • $object_id — Object ID or zero for all
  • $meta_key — Identify of the meta knowledge
  • $meta_value — Worth of the meta knowledge
  • $delete_all — Delete all meta knowledge

So wanting on the above method, we move the next arguments for these 5 parameters:

  • publish — We need to choose publish objects
  • zero — We use zero to pick all posts
  • myplugin_meta_key — The identify of our metadata
  • (empty) — Depart clean to pick all
  • true — Essential to set as true to delete all matching outcomes

As one may think, delete_metadata() could be very versatile and highly effective, enabling deletion of nearly any meta knowledge that exists within the WordPress database.

Full uninstall.php instance

Properly, virtually full. This subsequent code snippet consists of most of the examples offered on this tutorial. It does not embrace all of them, just one snippet from every method. Superior and alternate methods aren't included.

<?php
/*
        Instance uninstall.php file
        Incorporates examples offered within the tutorial:
        WordPress uninstall.php file - The Full Information
        @ https://digwp.com/2019/10/wordpress-uninstall-php/
*/

// exit if uninstall fixed isn't outlined
if (!outlined('WP_UNINSTALL_PLUGIN')) exit;

// delete plugin choices
delete_option('myplugin_options');

// delete plugin transient
delete_transient('myplugin_transient');

// delete cron occasion
$timestamp = wp_next_scheduled('myplugin_cron_event');
wp_unschedule_event($timestamp, 'myplugin_cron_event');

// delete database desk
international $wpdb;
$table_name = $wpdb->prefix .'myplugin_table';
$wpdb->question("DROP TABLE IF EXISTS $table_name");

// delete pages
$myplugin_pages = get_option('myplugin_pages');
if (is_array($myplugin_pages) && !empty($myplugin_pages)) 
        foreach ($myplugin_pages as $myplugin_page) 
                wp_trash_post($myplugin_page);
        


// delete customized publish sort posts
$myplugin_cpt_args = array('post_type' => 'myplugin_cpt', 'posts_per_page' => -1);
$myplugin_cpt_posts = get_posts($myplugin_cpt_args);
foreach ($myplugin_cpt_posts as $publish) 
        wp_delete_post($post->ID, false);


// delete consumer meta
$customers = get_users();
foreach ($customers as $consumer) 
        delete_user_meta($user->ID, 'myplugin_user_meta');


// delete publish meta
$myplugin_post_args = array('posts_per_page' => -1);
$myplugin_posts = get_posts($myplugin_post_args);
foreach ($myplugin_posts as $publish) 
        delete_post_meta($post->ID, 'myplugin_post_meta');

This code is supposed to be added to a clean/empty uninstall.php file. Hopefully this helps anybody who needs to get began shortly. Keep in mind extra methods and variations of included methods might be discovered elsewhere on this tutorial. Have enjoyable :)

Phrase to the clever

As helpful as uninstall.php could also be, it is very important watch out when eradicating any knowledge from the database. For instance in some instances, customers might uninstall a plugin by accident or briefly. So if the consumer has configured choices or different knowledge for the plugin, they could be extraordinarily upset to seek out that modifications have been misplaced.

To assist forestall such accidents, it might be a good suggestion to offer an choice that asks customers in the event that they need to take away all knowledge when the plugin is uninstalled. Like a checkbox choice that could be checked within the uninstall.php file, earlier than any knowledge is eliminated. That could possibly be so simple as including this line:

if (!get_option('plugin_do_uninstall', false)) exit;

That method you possibly can examine whether or not or not the consumer truly needs to take away knowledge when the plugin is uninstalled. This system can forestall undesirable knowledge loss and upset, confused customers. All the time consider the consumer, is my greatest recommendation :)

if (tutorial_complete()) exit;

It is nice to assist customers with superior plugins. Plugins that clear up after themselves are merely the BEST. In case your plugin makes any modifications to the WordPress database, greatest follow is to make sure that every little thing is restored to unique circumstances when the plugin is uninstalled. In some instances, meaning eradicating all added knowledge and restoring any modified knowledge. In different instances, you might need to take away solely sure kinds of knowledge.

For instance, my free WordPress plugin User Submitted Posts allows customers to submit posts from the front-end of the location. So its uninstall.php file removes solely the plugin choices; it does NOT take away any of the user-submitted posts from the database. So it's a must to be sensible about which knowledge to take away.

Backside line: It's your duty as a plugin developer to make sure that the suitable knowledge is eliminated and/or restored when your plugin is uninstalled. As defined on this tutorial, including a well-equipped uninstall.php file is a simple, constant, and dependable solution to make it occur.

Comments