Skip to content

Instantly share code, notes, and snippets.

@kellenmace
Last active October 9, 2023 03:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellenmace/539e9e30c3836f34896543daed83a8e4 to your computer and use it in GitHub Desktop.
Save kellenmace/539e9e30c3836f34896543daed83a8e4 to your computer and use it in GitHub Desktop.
Keep track of all transients that could exist in an option so that you can delete them by prefix. Useful for deleting dynamically generated keys on sites with a persistent object cache. Note: be careful with garbage collection - only use this when there is a finite number of possible transient keys.
<?php
/**
* Set/update the value of a transient.
*
* Transients set using this function can later be deleted in bulk
* based on their prefix using rth_delete_transients().
*
* @param string $key Transient key.
* @param mixed $value Transient value.
* @param int $expiration Optional. Time until expiration in seconds.
* @return bool False if value was not set and true if value was set.
*/
function rth_set_transient( $key, $value, $expiration = 0 ) {
$was_transient_set = set_transient( $key, $value, $expiration );
if ( $was_transient_set ) {
// Add key to the list of transient keys that could potentially exist.
$transient_keys = get_option( 'rth_transient_keys' );
$transient_keys[] = $key;
update_option( 'rth_transient_keys', array_unique( $transient_keys ) );
}
return $was_transient_set;
}
/**
* Delete all transients with a key prefix.
*
* This function will only delete transients that were originally
* set using rth_set_transient().
*
* @param string $prefix Prefix to search for.
* @return int|bool Count of total deleted or false on failure.
*/
function rth_delete_transients( $prefix ) {
// Get transient keys that could potentially exist.
$transient_keys = get_option( 'rth_transient_keys' );
$total_deleted = 0;
if ( $transient_keys && is_array( $transient_keys ) ) {
foreach ( $transient_keys as $index => $key ) {
// If transient key starts with the prefix we're looking for,
if ( substr( $key, 0, strlen( $prefix ) ) === $prefix ) {
// Delete transient.
$was_transient_deleted = delete_transient( $key );
if ( $was_transient_deleted ) {
// Remove transient from the keys that could potentially exist.
unset( $transient_keys[ $index ] );
$total_deleted++;
}
}
}
update_option( 'rth_transient_keys', array_values( $transient_keys ) );
}
return $total_deleted ? $total_deleted : false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment