In WordPress development, we often need to save and retrieve simple data in our database.
By using get_options and update_options in WordPress this thing become super easy.
Let’s say we want to save and retrieve a data called “User’s age”. First of all, we need add an option for that if we don’t have it yet. So we check, if there is no option with that name, we add it.
Specifically this way:
if(!get_option("wp_user_age")){
add_option("wp_user_age", "");
}
That code is telling WordPress that if there is no option with key “wp_user_age”, so add it with default value of empty string.
Then, to save a new value to it, we call update_option this way:
update_option("wp_user_age", "25");
That code is telling WordPress to set the value 25 to user’s age. You know it’s just an example, you can pass “25” string or 25 integer, I don’t think there will be any problem.
Then, to retrieve the value of wp_user_age, we call:
echo get_option("wp_user_age");
This line will echo the value of that option to web browser.