How to Use update_option in WordPress: Syntax and Examples
Use the
update_option function in WordPress to save or update a named option in the database. It takes two main arguments: the option name as a string and the new value to store. If the option exists, it updates it; if not, it creates it.Syntax
The update_option function has this syntax:
- option_name: The name of the option you want to update or add, as a string.
- new_value: The new value to save for this option. It can be any data type.
- autoload (optional): Whether to load this option automatically. Defaults to 'yes'.
It returns true if the option was updated or added successfully, otherwise false.
php
bool update_option( string $option_name, mixed $new_value, string $autoload = 'yes' )Example
This example shows how to update the site administrator's email address stored in the option admin_email. If the option does not exist, it will be created.
php
<?php // Update the admin email option $updated = update_option('admin_email', 'newadmin@example.com'); if ($updated) { echo 'Option updated successfully.'; } else { echo 'Option update failed or no change was made.'; } ?>
Output
Option updated successfully.
Common Pitfalls
Common mistakes when using update_option include:
- Using an incorrect option name that does not match the stored option.
- Expecting
update_optionto always returntrue— it returnsfalseif the new value is the same as the old one. - Not serializing complex data structures before saving (WordPress handles this automatically).
Example of a wrong and right approach:
php
<?php // Wrong: expecting true even if value is unchanged $updated = update_option('site_name', 'My Site'); if ($updated) { echo 'Updated'; } else { echo 'Not updated or no change'; } // Right: check if option exists first or handle false return properly $old_value = get_option('site_name'); $new_value = 'My Site'; if ($old_value !== $new_value) { update_option('site_name', $new_value); echo 'Option updated'; } else { echo 'No change needed'; } ?>
Output
No change needed
Quick Reference
Tips for using update_option effectively:
- Always use a unique and consistent option name.
- Use
get_optionto check current values before updating. - Remember
update_optionreturnsfalseif the value is unchanged. - WordPress automatically serializes arrays and objects for you.
- Use the optional
autoloadparameter to control loading behavior.
Key Takeaways
Use
update_option to add or update settings in the WordPress database by option name.It returns true only if the option was added or changed; false means no change or failure.
Check existing option values with
get_option before updating to avoid unnecessary writes.WordPress handles serialization of complex data automatically when saving options.
Use the optional autoload parameter to control if the option loads on every page load.