Is get_option function cached?

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.

Leave a Comment