Is get_option function cached?

In my plugin, I use the following code to retrieve an option from the database:

$options = get_option('my_plugin_options');

If I use this 10 times in various functions of my plugin, does WordPress make 10 queries to the database, or does it only make 1 database call per HTTP request and cache the results?

Related posts

2 comments

  1. When in doubt, look at the source code.

    Digging in to get_option(), you’ll see (abbreviated):

     $value = wp_cache_get( $option, 'options' );
    
    if ( false === $value ) {
        $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
    
        // Has to be get_row instead of get_var because of funkiness with 0, false, null values
        if ( is_object( $row ) ) {
            $value = $row->option_value;
            wp_cache_add( $option, $value, 'options' );
        } else { // option does not exist, so we must cache its non-existence
            $notoptions[$option] = true;
            wp_cache_set( 'notoptions', $notoptions, 'options' );
            return apply_filters( 'default_option_' . $option, $default );
        }
    }
    

    First, WordPress checks to see if it already has the option in memory. By default, wp_cache_get() will retrieve values from an in-memory data store (usually just a PHP variable). But some installations use a more advanced object cache which stores the data elsewhere.

    In either case, wp_cache_get() will return your option value if WordPress already knows it.

    If not, then WordPress will try to grab it from the database. If the option exists in the DB, then WordPress will cache it in memory and then give it back – making subsequent lookups faster.

    If the option doesn’t exist in the database, then WordPress flags it in an internal “these options don’t exist” array so it doesn’t try to look it up later and returns some default value instead.

    So, to answer your original question:

    If I use this 10 times in various functions of my plugin, does WordPress make 10 queries to the database, or does it only make 1 database call per HTTP request and cache the results?

    WordPress will make 1 database call per HTTP request and cached the results.

  2. Yes, it is cached. Look at the function’s source. It calls wp_load_alloptions() in background, to fetch all options, and that function adds the result to the cache:

    wp_cache_add( 'alloptions', $alloptions, 'options' );
    

    If you look at the class WP_Object_Cache in wp-includes/cache.php, you will see, it is possible for every plugin to call the public method flush().

    In this case the option value is not cached anymore, and get_option() will trigger a new database lookup. Plugins shouldn’t do this, but to be sure you are not affected, do not call the cache directly, always use just get_option().

Comments are closed.