0
0
Wordpressframework~30 mins

Uninstall and cleanup hooks in Wordpress - Mini Project: Build & Apply

Choose your learning style9 modes available
WordPress Plugin Uninstall and Cleanup Hooks
📖 Scenario: You have created a WordPress plugin that stores some settings and creates a custom database table. Now you want to make sure that when the plugin is uninstalled, all its data is cleaned up properly.
🎯 Goal: Build a WordPress plugin that uses the uninstall hook to remove plugin options and drop the custom database table when the plugin is uninstalled.
📋 What You'll Learn
Create an array called $my_plugin_options with exact keys and values
Create a variable called $table_name with the exact table name
Write a function called my_plugin_uninstall that deletes all options in $my_plugin_options and drops the table $table_name
Register the uninstall hook using register_uninstall_hook with the function my_plugin_uninstall
💡 Why This Matters
🌍 Real World
Plugins often store data in the database. Cleaning up on uninstall prevents leftover clutter and keeps the site clean.
💼 Career
Knowing how to properly use uninstall hooks is essential for WordPress plugin developers to maintain good plugin hygiene and user trust.
Progress0 / 4 steps
1
Setup plugin options and table name
Create an array called $my_plugin_options with these exact keys and values: 'setting_one' => 'value1', 'setting_two' => 'value2'. Also create a variable called $table_name and set it to $wpdb->prefix . 'my_plugin_table'.
Wordpress
Need a hint?

Use array() to create $my_plugin_options and concatenate $wpdb->prefix with the table name for $table_name.

2
Define the uninstall function
Write a function called my_plugin_uninstall that uses global $wpdb. Inside it, loop over $my_plugin_options keys and delete each option using delete_option. Then drop the table $table_name using $wpdb->query with the SQL DROP TABLE IF EXISTS.
Wordpress
Need a hint?

Use foreach to loop over the keys of $my_plugin_options and call delete_option for each. Use $wpdb->query to drop the table.

3
Register the uninstall hook
Use register_uninstall_hook with __FILE__ and the function name 'my_plugin_uninstall' to register the uninstall cleanup.
Wordpress
Need a hint?

Call register_uninstall_hook with __FILE__ and the uninstall function name as a string.

4
Add plugin header comment
Add the WordPress plugin header comment at the top of the file with these exact lines: Plugin Name: My Cleanup Plugin, Description: A plugin that cleans up on uninstall, Version: 1.0, Author: Your Name.
Wordpress
Need a hint?

The plugin header comment must be at the very top of the file inside /* ... */.