Now that you know how to create a new option for your plugin, let's look at updating that option value. To handle this, you'll use the update_option()
function. As an example, let's update the color of your new plugin setting from red to blue.
The update_option()
function accepts the following parameters:
option: Name of the option to update
value: Value of the option you are updating
autoload: Whether to load the option when WordPress starts
The difference between add_option()
and update_option()
is that the first function does nothing if the option name already exists, whereas update_option()
checks if the option already exists before updating its value and creates it if needed.
To fetch an option value from the database, use the function get_option()
.
The first thing to know about get_option()
is that if the option does not exist, it will return false
. The second thing is that if you store Booleans, you might get integers in return.
The get_option()
function accepts the following parameters:
option: Name of the option to retrieve
default: Value to return if the option does not exist. The default return value is false.
As an illustration of this behavior, consider the following code block that creates a couple of new options with various variable types:
You can now retrieve these options, along with another one that does not exist, and see what variable types are returned, shown as an inline comment below each get_option()
call:
To avoid an error when checking option values, you should store true
and false
as 1
and 0
. This means also that you need to strictly compare the return of get_option()
with Boolean false
to check if the option exists.
You can also specify what value you want to be returned if the option is not found in the database, with a second option parameter to get_option()
, like in the following example:
Loading an Array of Options
You have seen that saving multiple options in a single array is best practice. A complete example of saving and then getting values from one array would be as follows:
Saving and retrieving options enclosed in an array has another advantage: variable Boolean types within the array are preserved. Consider the following example:
Now get the option value from the database with var_dump( get_option( 'test_bool' ) )
. See how Boolean types are retained, contrary to the previous example:
// output result var_dump( get_option( 'pdev_test_bool' ) ); array(2) { ["booltrue"] => bool(true) ["boolfalse"]=> bool(false) }
Now that you understand how to create, update, and retrieve options, let's look at deleting an option. Deleting an option needs a self‐explanatory function call.
This function call returns false
if the option to delete cannot be found and returns true
otherwise. You will mostly delete options when writing uninstall functions or files (see Chapter 2).
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:
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.
Segregating Plugin Options
A function to initiate your plugin options, run on plugin activation as covered in Chapter 2, could then look like the following:
Again, don't forget the empty third parameter before the autoload
value. This might seem a bit convoluted, and actually it is for so few options set. This professional technique makes sense if your plugin features dozens of options, or options containing long text strings.
NOTE As a rule of thumb, if your options are needed by the public part of the blog, save them with autoload
. If they are needed only in the admin area, save them without autoload
.
Toggling the Autoload Parameter
The autoload
parameter is set when an option is created with add_option()
and is not supposed to change afterward. With this said, if you believe that it would improve your plugin's efficiency to modify the autoload
behavior, it is possible and easy: simply delete and then re‐create the option with an explicit autoload
parameter.
Options can be internally created and updated by your plugin (for instance, storing the time stamp of the next iteration of a procedure). But they are also frequently used to store settings the end user will modify through your plugin administration page.
When creating or updating user‐defined options for a plugin, relying on the Settings API can make your code both simpler and more efficient.
Benefits of the Settings API
Dealing with user inputs introduces new constraints in the option process: you need to design a user interface, monitor form submissions, handle security checks, and validate user inputs. To easily manage these common tasks, WordPress wraps the option functions into a comprehensive Settings API.
The Settings API enables you to handle these simple tasks:
Tell WordPress that you are going to use some new options and how you want them displayed.
Specify a function that will sanitize user inputs.
while WordPress transparently manages for you these cumbersome and repetitive parts:
Draw most of the option page itself.
Monitor form submission and handle $_POST data.
Create and update options if needed.
Wield all the required security measures and hidden fields for nonces, covered in detail in Chapter 4, “Security and Performance.”
Читать дальше