uninstall.php file in Plugin to clean DB

I am aware that WordPress provides Plugins a nice way to clean up the db if the Plugin is deleted by providing the uninstall.php hook. You just have to place the cleaning code and it works.

But my question is, I have seen a couple of Plugins which is using functions defined in their Plugin file inside the uninstall.php file. My understanding is that if the Plugin is already disabled and the user is deleting it after that, then these functions may not be accessible.

Read More

Is my assumption correct or is there any WordPress magic which I am not aware of?

Related posts

Leave a Reply

1 comment

  1. I have seen a couple of Plugins which is using functions defined in their Plugin file inside the uninstall.php file.

    That doesn’t work, if the uninstall.php calls one of the plugin’s functions, it will produce a Fatal error: Call to undefined function. Unless… (explained bellow).

    This, on the other hand, works:

    <?php
    /* Plugin Name: Test Uninstall */
    register_activation_hook( __FILE__, 'test_activate' );
    register_uninstall_hook( __FILE__, 'test_uninstall' );
    
    function test_activate()  { update_option( 'testing_uninstall', true ); }
    function test_uninstall() { test_delete_me(); }
    function test_delete_me() { delete_option( 'testing_uninstall' ); }
    

    We can see why in the function uninstall_plugin(). If unistall.php exists, it is included, executed and end of story.
    If no uninstall.php file exists, and if we registered the uninstall hook, the main plugin file will be included: include WP_PLUGIN_DIR . '/' . $file;, so as to make the callback available -and thus making the other function available too.

    We could make some includes in our uninstall.php file, but is the uninstall process so complex as to need this?

    A quote from a related wp-hackers thread (my emphasis):

    [T]he uninstall hook is stored within the database, its not determined at run time. Your plugin will not recieve init/plugins_loaded/admin_init, etc hook firings when the uninstall hook is called, it’s a pure “Heres some SELF CONTAINED code to run to clean up”