WordPress comes with many functions for database manipulations. This is done to minimize the use of unsecure database queries. We’re going to go over a couple of these basic options today.
If a plugin wants to store small amounts of data in the blog’s database, it can store it in the wp_options table. This is the table where many of WordPress’ options are stored, along with other plugins. WordPress provides a set of functions for add, updated, retrieving and deleting options stored in the wp_options table.
To retrieve (SELECT) an option from the option table in the database, we can use the get_option function. This function only accepts one parameter, the name of the option you would like to retrieve (it will return it back to you).
We can use one of two functions to create an option. Let’s start out with the add_option function. Its syntax is as follows:
[code='php']add_option($name, $value, $deprecated, $autoload);[/code]
$name is the name of the option, this should be as unique as possible to avoid name collisions with other options stored in the table. $value is the initial value of the option. $deprecated is there for backward compatiability purposes, just pass a blank string or null if you want to specify the next parameter. $autoload is either “yes” or “no” (default is “yes”), if yes the option will be retrieved by the get_alloptions function. Only $name is required.
The function we use to update an option will also create the option if it doesn’t already exist. Its syntax is:
Both parameters are required. $name should be a string and $value can be a string, array or object. It’s worth noting that many arrays used in options are stored as serialized values in the database.
To delete an option, you can use the delete_option function. It accepts one parameter, the name of the option you would like to delete. It will return true on the successful deletion of the option, and false if otherwise. Note, that it will not allow you to delete some protected WordPress options.
Next week we’ll go over some other functions to do more advanced manipulations of the of WordPress database.