By default, whenever you add or update an option via add_option or update_option in WordPress, that option is automatically loaded from the database on every request. This is not necessarily what you want. Especially if you have options with much content, it’s probably better to only load them when necessary.

Background

Both the add_option and update_option have a parameter to allow auto-loading the values. While it’s default to yes for add_option, the default for update_option is null, which translates to yes. This value directly translates to the autoload column in the database table of wp_options.

On every load, WordPress uses the wp_load_alloptions function to load all options having the autoload column set to yes in the database.

Get option size

First thing on optimizing is to check whether it’s necessary. Usually, I think if the values are rather small, there is no real benefit in setting the autoload value to no since if you need it, WordPress would create another database query exclusively for this option.

So I would start by looking into the current size of the different options. This can be done using this MySQL query:

SELECT		option_name, LENGTH(option_value) AS option_size
FROM		wp_options
WHERE		autoload = 'yes'
ORDER BY	option_size DESC;Code language: SQL (Structured Query Language) (sql)

If you just want to know the sizes of your own plugin’s options, you can adjust the WHERE clause of course, e.g. by limiting the output on option_name, like this:

SELECT		option_name, LENGTH(option_value) AS option_size
FROM		wp_19_options
WHERE		option_name LIKE '%embed_privacy_%'
AND			autoload = 'yes'
ORDER BY	option_size DESC;Code language: SQL (Structured Query Language) (sql)

Both times you will get an output with the columns of the option name and its size, where it’s size is the amount of characters being stored.

Select options to auto-load

If your options are required most of the time, always auto-load them. But if your options contain data, which are used partly on the frontend and partly in the backend, try splitting them in separate options.

If your options are only required in the backend, it can be a good reason to only load them manually in the backend.

Please keep in mind that for every option that is not set to be auto-loaded, an additional database query will be required as soon as the option is used. So for rather small options, e.g. boolean options, there is no benefit in loading them manually, since the impact for an additional database query would be much higher.

Update the option

In your code, just set the autoload value for add_option and update_option to no. For add_option, it’s the fourth parameter, for update_option it’s the third.

Keep in mind that update_option will only update the autoload value in the database if the value of the option itself changes, too.

Leave a Reply

Your email address will not be published. Required fields are marked *