Skip to content

Instantly share code, notes, and snippets.

@soderlind
Last active Sep 25, 2021
Embed
What would you like to do?
WordPress Multisite, gets all site transient keys in the database with a specific prefix.
<?php
foreach ( get_site_transient_keys_with_prefix( 'my_tranients_prefix_' ) as $transient ) {
delete_site_transient( $transient );
}
<?php
/**
* Gets all site 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.
*
* Inspired by: https://kellenmace.com/delete-transients-with-prefix-in-wordpress/
*
* @param string $prefix Prefix to search for.
* @return array Transient keys with prefix, or empty array on error.
*/
function get_site_transient_keys_with_prefix( $prefix ) {
global $wpdb;
$network_id = get_current_network_id();
$keys = $wpdb->get_results(
$wpdb->prepare(
"SELECT meta_value, meta_key FROM {$wpdb->sitemeta}
WHERE meta_key LIKE %s AND site_id = %s",
$wpdb->esc_like( '_site_transient_' . $prefix ) . '%',
$network_id
),
ARRAY_A
);
if ( is_wp_error( $keys ) ) {
return [];
}
return array_map(
function( $key ) {
// Remove '_site_transient_' from the option name.
return str_replace( '_site_transient_', '', $key['meta_key'] );
},
$keys
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment