How to Use Update Option In WordPress

How to Use Update Option In WordPress

In this post, I want to help you understand how to use the update option in WordPress to save data in your options table.

If you are developing a WordPress plugin or WordPress theme, you will obviously require an update option function to save the data in the database.

The best place to begin is to understand how the update option works and then share an example of how you can apply it in your development process.

Update Option Function

The update option function allows you to update the value of an option in the wp_options table and save the data.

This is the general expression of the update_option function:

update_option( string $option, mixed $value, string|bool $autoload = null )

The following are the parameters that you apply to the update option function:

Parameter Description
$option (string) (Required) Name of the option to update. 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 WordPress starts up. For existing options, $autoload can only be updated using update_option() if the $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: null

How to Use the Update Option In WordPress

To use the update_option function you should create the option name and the value of the option you have created. The following is an example of how you would use the update option to save the value.

Suppose we have a field for the first name and we need to use the update option to save the value that is added to the field.

We can achieve this by creating the option name for example  first_name as a string and get the value of the input field using the $_POST global object to get the value on the form and add it to the update option function  :

 

$first_name = esc_attr($_POST["first_name"]);

update_option("first_name", $first_name);


This is how you can use the update option in WordPress to save the value of the input field named first name. The input field can have the markup as follows:

<p>

<input type="text" name="first_name"    value=" "/>

</p>

 

Conclusion 

In this post, we have looked at how to use the update option in WordPress to save the value of an option into the WordPress database.

If you have multiple values you can use serialization to put the data into an array and save it easily.

To retrieve this data from the database you should use the get_option() and you should use the option name you created when saving the data in the step above with the update_option function.

Similar Articles

  1. How to Add Custom Shipping Method in WooCommerce