Last active
March 22, 2024 17:14
-
-
Save kellenmace/7d8f3b4c48cef3fd68ebc8606415d7dd to your computer and use it in GitHub Desktop.
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
<?php | |
/** | |
* Delete all transients from the database whose keys have a specific prefix. | |
* | |
* @param string $prefix The prefix. Example: 'my_cool_transient_'. | |
*/ | |
function delete_transients_with_prefix( $prefix ) { | |
foreach ( get_transient_keys_with_prefix( $prefix ) as $key ) { | |
delete_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 ); | |
} |
@kellenmace I just ran into the same error. The fix in the code isn’t there when I look at the blog post on https://kellenmace.com/delete-transients-with-prefix-in-wordpress/. Somehow the Gist didn’t update on your website?
Just found this via a quick google search and it's exactly what I need. Working well. Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @drinkmaker - good catch. I have updated the code based on your suggested fix.