Skip to main content

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():
  • When you know the database has been modified by external means or another part of your code that doesn't use wpdb's caching mechanisms. 
    If you're directly interacting with the database outside of the standard wpdb methods, or if another system is modifying the data, flush() can ensure your wpdb queries reflect the latest state.
  • During development or debugging: 
    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:
Code
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'" );