Can I force get_option to go back to the DB instead of cache?

Is there any way to guarantee that when I call get_option I will definitely get the value from the database and not from cache?

Related posts

3 comments

  1. You could delete an existing cache for your option before you call get_option():

    $GLOBALS['wp_object_cache']->delete( 'your_option_name', 'options' );
    $value = get_option( 'your_option_name' );
    
  2. Using the wp_cache_delete() technic showcased by toscho, you also have to make sure your option is not on autoload. If your option is autoloaded, it’ll be part of the alloptions cache so you won’t be able to clear it individually.

    So make sure to use the following format when you set/update your option if you want to be able to clear it from the cache:

    update_option( 'my_key', 'my val', false ); // False being the autoload parameter
    
    add_option( 'my_key', 'my val', null, false ); // null is a deprecated argument.
    

    update_option() documentation

  3. Bit old question but I’ll add my piece of information.

    I’m using WP REDIS CACHE and notified that some of my get_option were returning a cached value, instead of the real DB value. I tried @fuxia solution, but I guess this concerns autoloading. And REDIS cache was applying cache on a “lower level”.

    I ended up with something to directly get some of my option from DB so I’m sure the value is correct: (in this example, my option name is my_option_name)

    function bypass_cache_custom_options_key($val, $opt)
    {
        try {
            global $wpdb;
            $query = $wpdb->get_results("SELECT * FROM $wpdb->options WHERE " . $wpdb->options . ".option_name = '$opt'");
    
            return $query[ 0 ]->option_value;
        } catch (Exception $e) {
    
        }
    
        return $val;
    }
    
    add_filter('pre_option_my_option_name', 'bypass_cache_custom_options_key', 1, 2);
    

    see pre_get_option

Comments are closed.