Читать книгу Professional WordPress Plugin Development - Brad Williams - Страница 83
The Autoload Parameter
ОглавлениеBy default, all the options stored in the database are fetched by a single SQL query when WordPress initializes and then caches. This applies to internal WordPress core settings and options created and stored by plugins.
This is efficient behavior: no matter how many get_option()
calls you issue in your plugins, they won't generate extra SQL queries and slow down the whole site. Still, the potential drawback of this autoload technique is that rarely used options are always loaded in memory, even when not needed. For instance, there is no point in fetching backend options when a reader accesses a blog post.
To address this issue when saving an option for the first time, you can specify its autoload behavior, as in the following example:
<?php add_option( 'pdev_plugin_option', $value, '', $autoload ); ?>
Note the empty third parameter: This is a parameter that was deprecated several WordPress versions ago and is not needed any more. Any value passed to it will do; just be sure not to omit it.
The fourth parameter is what matters here. If $autoload
is anything but 'no'
(or simply not specified), option pdev_plugin_option
will be read when WordPress starts, and subsequent get_option()
function calls will not issue any supplemental SQL query. Setting $autoload
to 'no'
can invert this: this option will not be fetched during startup of WordPress, saving memory and execution time, but it will trigger an extra SQL query the first time your code fetches its value.
NOTE If you want to specify the autoload parameter, you need to use add_option()
instead of update_option()
when creating an option the first time. If you don't need this parameter, always using update_option()
to both create and update will make your code more simple and consistent.
Of course, specifying the autoload parameter upon creation of an option does not change the way you fetch, update, or delete its value.