I see many plugins to get their options (one or more) with the super useful get_option() of WordPress not only once but every time they needed it and sometime more than once inside the same function.

This is definitively not good for performances. Let me explain why.

Admitting your options are “autoloaded”, your get_option() does not trigger a query to the database but every time you call it:

  • the option name is trimmed
  • the filter “pre_option_nnn” is called
  • the list of missing option is taken from the cache and checked
  • the list of autoloaded options is checked (probably creating a big array copy)
  • the option name is checked against ‘siteurl’, ‘home’, ‘category_base’, ‘tag_base’ special names
  • the maybe_unserialized is called over your option value
  • the filter “option_nnn” is applied

Reference: the options.php file of WordPress.

Every step is taken every time you call get_option(). It’s time to optimize that!

How to optimize the get_option() call?

First, use it as late as possible. Why? Suppose you created a plugin which just runs a shortcode. If that shortcode depends on a set of options but it is rarely used, why to run code which is not required?

To optimize the options load you can code it in this why (my example uses functions to be easy, but you should always wrap the code in a class). I assume you save all the options in an array (WordPress takes care to serialize and unserialize it).

$my_options = null;

function my_init_options() {
  global $my_options;
  if (!$my_options) {
    $my_options = get_option('my_options_name');

function my_something_to_do() {
  global $my_options;
  // my code here

As you can not the options are not returned by “my_init_options()” to avoid an array copy and because they anyway are global. Using a class and an internal property for your options makes the code less “dirty” and less “old style”. Optimized code most of the times is not elegant.

Let start the discussion, now!

Similar Posts

Leave a Reply