wpdb::flush
The
wpdb::flush() method in WordPress is used to clear the internal cache of the wpdb object.When you perform database queries using the
wpdb class (e.g., $wpdb->get_results(), $wpdb->query()), WordPress often caches the results of these queries internally within the wpdb object to improve performance. This means that if the same query is executed multiple times within a single request, the cached result might be returned instead of re-querying the database.Calling
wpdb::flush() will clear this internal cache, forcing wpdb to re-query the database for subsequent operations, even if the same query was previously executed and cached.When to use
wpdb::flush():-
If you're directly interacting with the database outside of the standard
wpdbmethods, or if another system is modifying the data,flush()can ensure yourwpdbqueries reflect the latest state. -
If you're seeing unexpected cached results and need to ensure you're always getting fresh data from the database,
flush()can be helpful.
Example:
global $wpdb;
// Perform a query, results are cached
$results1 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_name = 'my_option'" );
// Clear the wpdb internal cache
$wpdb->flush();
// Perform the same query again, it will now re-query the database
$results2 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_name = 'my_option'" );