I have no idea why this is not working. It finds the names that i want, but does not delete the transients, when the plugin is deactivated. According to the documentation, the name is required for this function. But it doesn’t do what is expected.
function pl_clear_db() {
global $wpdb;
$table_name = $wpdb->prefix . 'this_name';
$wpdb->query( "DROP TABLE IF EXISTS $table_name" );
$sql = "SELECT `option_name` AS `name`, `option_value` AS `value`
FROM $wpdb->options
WHERE `option_name` LIKE '%transient_%'
ORDER BY `option_name`";
$transients = $wpdb->get_results( $sql );
$all_trans = json_decode(json_encode($transients), true);
foreach ( $all_trans as $trans ) {
if (str_contains($trans['name'], '_needle_')){
delete_transient($trans['name']);
}
}
}
register_deactivation_hook( __FILE__, 'pl_clear_db' );
What’s wrong here? Hints are welcome.
Why it is not working (probably):
Probably you are passing the parameter onto delete_transients() wrong way. The delete_transients(parameter) accepts only the transient key name.
For example:
Your key is "my_key". It is stored in database as:
_option_name = _transient_my_key;
When you use delete_transient($trans['name']); , it passes "_transient_my_key" where the function only accepts "my_key".
Probable solution:
Remove the term _transient _ before passing the parameter and try again.
Source Code:
function pl_clear_db() {
global $wpdb;
$table_name = $wpdb->prefix . 'this_name';
$wpdb->query( "DROP TABLE IF EXISTS $table_name" );
$sql = "SELECT option_name FROM $wpdb->options WHERE option_name LIKE '_transient_%needle_%'";
$transients = $wpdb->get_col( $sql );
foreach ( $transients as $transient ) {
// Remove the '_transient_' prefix
$key = str_replace( '_transient_', '', $transient );
delete_transient( $key );
}
}
register_deactivation_hook( __FILE__, 'pl_clear_db' );
Note: Keep backup of your db before performing any operations. Do cross check whether anything illogical is provided or not.