This post is part of the ClassicPress Plugin Development series in which I am going to look at both best practice for developing plugins and how I approach some requirements as well as some of the functions I commonly use.
When developing a plugin, most of them will have settings which need to be saved ad recalled. There are functions available in ClassicPress which you can use to do this:
get_option
update_option
If your plugin contains multiple options, then best practice would be to store these in an array within one option rather than each option stored individually.
The get_option
is used to load options from the database:
get_option( string $option, mixed $default = false )
Parameters
$option (string) (Required) Name of option to retrieve. Expected to not be SQL-escaped.
$default (mixed) (Optional) Default value to return if the option does not exist.
Default value: falseReturn
(mixed) Value set for the option.
The below is an example of loading options from my SMTP plugin:
$options = get_option( 'azrcrv-smtp' );
The update_option
function is used to save options:
update_option( string $option, mixed $value, string|bool $autoload = null )
Parameters
$option (string) (Required) Option name. Expected to not be SQL-escaped.
$value (mixed) (Required) Option value. Must be serializable if non-scalar. Expected to not be SQL-escaped.
$autoload (string|bool) (Optional) Whether to load the option when ClassicPress starts up. For existing options, $autoload
can only be updated using update_option()
if $value
is also changed. Accepts 'yes'|true to enable or 'no'|false to disable. For non-existent options, the default value is 'yes'.
Default value: nullReturn
(bool) False if value was not updated and true if value was updated.
The below is an example of saving options from my SMTP plugin:
update_option( 'azrcrv-smtp', $options );
Click to show/hide the ClassicPress Plugin Development Series Index
What should we write about next?
If there is a topic which fits the typical ones of this site, which you would like to see me write about, please use the form, below, to submit your idea.