0

I am building a custom plugin and when the plugin is activated it creates 2 tables inside the wp database. What I want is, to add a checkbox is my custom plugin settings page, and if the checkbox is checked, the tables to be deleted from the database. I am using and uninstall.php file to delete my tables but that happens when I delete the plugin. I would like to fire that uninstall.php file which have the scripts to delete my tables, if the checkbox is checked.

Here is my code

<form action="options.php" method="POST" id="my-form">
<?php
    settings_fields("customfields");
    do_settings_sections("support");
    submit_button("Save Data");
    ?>
</form>
<p>Delete Database? <?php echo get_option("delete_database"); ?></p>
<?php
add_settings_section("section", null, null, "support");
add_settings_field("wp_delete_database", "Delete Database?", array($this, "HTML"), "support", "section");
register_setting("customfields", "wp_delete_database", array("sanitize_callback" => "sanitize_text_field", "default" => "Placeholder"));
?>
2
  • Inside uninstall.php just check get_option( 'delete_database' ); before doing anything. Jul 4, 2022 at 5:34
  • @JacobPeattie Thank you for ur reply. Can you give me a code example?
    – NoName84
    Jul 4, 2022 at 5:36

1 Answer 1

3
+25

You should have a function (single class, or method in a class) for the task to remove all the data from the plugin, like database or options entries.

On your settings page, call after an active checkbox this function, after sending a request, like via Button. In the uninstall.php have you also the possibility to use this function.

So you have only one function to do the same goal and no redundancy.

register_uninstall_hook

For the un-installion of the plugin via Core Function, Gui in the admin backend use the function register_uninstall_hook.

The uninstall.php

could look like this

<?php
/**
* Uninstallation script
* This file is called automatically by WP when the admin deletes the plugin from the installation.
*/
    
! defined( 'WP_UNINSTALL_PLUGIN' ) && exit;

require_once __DIR__ . '/src/settings.php';
// Use core function to delete items in the options table
delete_site_option( Your_Class_Settings::OPTION_NAME );
// Call method from class
Your_Class_Settings->uninstall();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.