You could do it using javascript and ajax. Javascript catches the click asks if you want to delete data if so it calls delete the data ajax in either case it continues to the deactivate.
add_action('admin_enqueue_scripts', 'deactivate_message_enqueue');
function deactivate_message_enqueue($hook) {
if ( 'plugins.php' != $hook ) {
// do not enqueue because it is not plugins page
return;
}
wp_register_script('deactivation-message', plugins_url('includes/js/message_deactivate.js', __FILE__), array(), SOW_VERSION);
$deleteParams = array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajax_nonce' => wp_create_nonce('nonce_salt'),
);
wp_localize_script('deactivation-message', 'deactivation_data', $deleteParams);
wp_enqueue_script('deactivation-message');
}
add_action( 'wp_ajax_hss_so_delete_all_tables', 'hssSoDeleteAllTablesAjax' );
function hssSoDeleteAllTablesAjax() {
global $wpdb;
// need to check nonce so it is secure.
$nonce = isset($_REQUEST['security']) ? sanitize_text_field($_REQUEST['security']) : '';
if ( ! wp_verify_nonce( $nonce, 'nonce_salt' ) ) {
wp_send_json_error(array('error' => 'Nonce invalid'));
}
// delete what you have to here
wp_send_json_success(array('error' => ''));
}
Then in the script file catch the url redirect of the deactivate and call ajax function to delete the data
includes/js/message_deactivate.js
window.onload = function(){
document.querySelector('[data-slug="plugin-slug"] .deactivate a').addEventListener('click', function(event){
event.preventDefault();
var urlRedirect = document.querySelector('[data-slug="plugin-slug"] .deactivate a').getAttribute('href');
if(confirm('Do you want to delete all the data created for this plugin?')) {
deleteAllPluginData();
}
window.location.href = urlRedirect;
})
}
function deleteAllPluginData(){
var data = 'action=delete_all_my_plugin_data&security=' + deactivation_data.ajax_nonce;
jQuery.ajax({
type : "post",
dataType : "json",
url : deactivation_data.ajax_url,
data : data,
success: function(response) {
if (response.success == true) {
console.log('All Data Deleted.');
} else {
console.log('There was an error deleting data: ' + JSON.stringify(response.data.error));
}
},
});
}
register_uninstall_hook()
should do the trick.