Last active
June 9, 2024 18:43
-
-
Save sabrina-zeidan/b0641e0956eb72ef4d5eaeaa70089c10 to your computer and use it in GitHub Desktop.
List or delete all transients with a specific prefix WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function delete_transients_with_prefix( $prefix ) { | |
foreach ( get_transient_keys_with_prefix( $prefix ) as $key ) { | |
// delete_transient( $key ); | |
echo "<br>". $key." ".get_transient( $key ); | |
} | |
} | |
/** | |
* Gets all transient keys in the database with a specific prefix. | |
* | |
* Note that this doesn't work for sites that use a persistent object | |
* cache, since in that case, transients are stored in memory. | |
* | |
* @param string $prefix Prefix to search for. | |
* @return array Transient keys with prefix, or empty array on error. | |
*/ | |
function get_transient_keys_with_prefix( $prefix ) { | |
global $wpdb; | |
$prefix = $wpdb->esc_like( '_transient_' . $prefix ); | |
$sql = "SELECT `option_name` FROM $wpdb->options WHERE `option_name` LIKE '%s'"; | |
$keys = $wpdb->get_results( $wpdb->prepare( $sql, $prefix . '%' ), ARRAY_A ); | |
if ( is_wp_error( $keys ) ) { | |
return []; | |
} | |
return array_map( function( $key ) { | |
// Remove '_transient_' from the option name. | |
return substr( $key['option_name'], strlen( '_transient_' ) ); | |
}, $keys ); | |
} | |
//To fire the function: | |
delete_transients_with_prefix( 'speedguard'); | |
//To return both keys and values | |
function get_transient_keys_with_prefix( $prefix ) { | |
global $wpdb; | |
$prefix = $wpdb->esc_like( '_transient_' . $prefix ); | |
$sql = "SELECT `option_name`, `option_value` FROM $wpdb->options WHERE `option_name` LIKE '%s'"; | |
$results = $wpdb->get_results( $wpdb->prepare( $sql, $prefix . '%' ), ARRAY_A ); | |
if ( is_wp_error( $results ) ) { | |
return []; | |
} | |
$transients = array(); | |
foreach ( $results as $result ) { | |
// Remove '_transient_' from the option name and store both the key and value | |
$key = substr( $result['option_name'], strlen( '_transient_' ) ); | |
$transients[$key] = maybe_unserialize( $result['option_value'] ); | |
} | |
return $transients; | |
} | |
//To fire the function: | |
function sz_output() { | |
$transients = get_transient_keys_with_prefix( 'speedguard' ); | |
echo '<pre>'; print_r($transients); echo '</pre>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment