Plugin options autoloading

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).

Leave a Comment