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?
When in doubt, look at the source code.
Digging in to
get_option()
, you’ll see (abbreviated):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:
WordPress will make 1 database call per HTTP request and cached the results.
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:If you look at the class
WP_Object_Cache
inwp-includes/cache.php
, you will see, it is possible for every plugin to call the public methodflush()
.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 justget_option()
.