Plugin options autoloading

In the book ‘Professional WordPress Development’ I found this tip:

As a rule of thumb, if your options are needed by the public part of the blog,
save them with autoload. If they are only needed in the admin area, save them
without autoload.

Read More

Wouldn’t that result in many extra SQL queries in the backend if all plugin developers followed that advice, thus slowing down the admin side?

What would be a good example of using autoload with plugin options?

Related posts

Leave a Reply

2 comments

  1. Quite personally I disagree with the author of the book to an extent. If you are auto-loading multiple options in your database when WordPress is initialising it’s doing a lookup that looks like this: *”SELECT option_name, option_value FROM wp_options WHERE autoload = ‘yes'”* — at the beginning. Now, imagine if you had 40 options, that’s 40 separate DB queries.

    However if you are only auto-loading a serialised array of options, that’s potentially hundreds of options within the option option stored as a serialised string. So it’s not entirely bad to auto-load only in the instance where you’re auto-loading more than one option at a time.

    I have seen plugins abuse the options API badly by having multiple options separately stored, it’s unnecessary overhead. So remember, always serialise unless there’s a good reason you don’t want too.

    The benefit of autoloading is that the options are cached. So when WordPress is initialised, the options are cached and hence more efficient. But like I said, if you have 80 separate options there will be an initial performance hit until they’re cached which is bad.

    Here is an example of serialising multiple options into the one:

    $myoptions = array(
        'option1' => 'option value',
        'option2' => 'option value 2',
        'option3' => 'option value 3'
    );
    
    update_option('theme_settings_field', $myoptions );
    
    $options = get_option('theme_settings_field');
    
    if ($options) {
        $option1 = $options['option1'];
    }
    

    As you can see in the example, you can serialise an array which from a database perspective is one option comprised of many options. When you retrieve the options, they’re unserialised into an array you can access (like the example shows above).

  2. By default options are auto-loaded and you need to do some effort to prevent that. If you create an option by using the update_option API it is created as auto-loading. To have a non auto-loading option you have to create it by calling add_option with the fourth parameter set to “no”. Due to the difference in the ease of API use I am guessing most options are autoloaded.

    Before going that route you should also consider this ticket in which it is claimed that wordpress.com just autoloads all options.