WordPress Add_option, Get_option, delete_option and Update_option
For every theme development and plugin development, we will have to store some configurations like the options and its values in our wordpress options table. WordPress already given us enough functions to perform this in easy way. Which will not requires to write more code on this. To add a new option we can call the add_option. And Retrieve the values, we can use the get_option and pass the key name, which will get us the results of it. Suppose if you passed any array, it will be stored in serialized and also it will get it back as array while using the get_option function.
Update_option helps to change the value of our option when it requires to modify. Most of the time, we will create separate options page to perform this. Even i have another article which helps to know that how to create options in separate page. So here let me give some examples to perform the options.
This is pretty first one to put an option in the options table. so lets start with an example.
add_option('kvcodes_save_preference', 'yes_this is the value');
The Above code works when you put in the plugin activation or your theme install. Incase if you are writing it inside pages. you might need to check whether such an option exist before add it. So lets enhance it a little bit
add_option('kvcodes_save_prefernce', 'Now this validated to avoid duplicate add options');
We have already used this function in our previous code to check whether the option exist or not. But the same code also helps to get the value and use it on our needy locations. E.g
$kvcodes_Save_preference = get_option('kvcodes_save_preference');
WordPress itself it checks whether the given variable is a string or array or object, if its not string or number, the system will auto serialize and save it in database. while getting it back,
$array_option = ['first' => 'First Text',
'second' => 'Second Text',
'third' => 'Third Text'];
//while getting it back, it will be like this.
$opt_ = get_option('kvcodes_save_array');
//Here opt_ gets the array back to use it.
echo $opt['first']; // First Text
Here you can able to update the values with existing options, like modifying the option requires to change in wordpress side as well. Let’s do this way.
update_option('kvcodes_save_preference', 'This is updated value');
When an option is not required. We should delete it periodically, otherwise the options table will be more junk and unnecessary load to your Database and site.
That’s it with WordPress options, its really easy to code.