Using WordPress ‘add_option()’ PHP function

The add_option() WordPress PHP function adds a new option to the WordPress database. It automatically serializes non-scalar values before inserting into the database. However, resources cannot be serialized or added as an option. This function also performs checks to prevent adding a protected WordPress option.

Usage

The add_option() function can be used as follows:

add_option( 'my_option_name', 'my_option_value', '', 'yes' );

In this example, a new option called ‘my_option_name’ is added with the value ‘my_option_value’. The option will be autoloaded on WordPress startup because the last parameter is ‘yes’.

Parameters

  • $option (string) (Required): Name of the option to add. Expected to not be SQL-escaped.
  • $value (mixed) (Optional): Option value. Must be serializable if non-scalar. Expected to not be SQL-escaped. Default: ”.
  • $deprecated (string) (Optional): Description. Not used anymore. Default: ”.
  • $autoload (string|bool) (Optional): Whether to load the option when WordPress starts up. Default is enabled. Accepts ‘no’ to disable for legacy reasons. Default: ‘yes’.

More information

See WordPress Developer Resources: add_option()

The autoload option allows WordPress to automatically fetch the option and its value on every page request, saving a database query when you request the option. However, the value of your option entry will add to the overall memory consumed by the website.

Examples

Add a Basic Option

In this example, we’re adding a simple option that holds a string value.

add_option( 'site_theme_color', 'blue' ); // Adds an option 'site_theme_color' with value 'blue'

Add an Option with an Array Value

You can also add an option that holds an array value.

add_option( 'featured_posts', array( 12, 15, 18, 21 ) ); // Adds an option 'featured_posts' with an array of post IDs

Add an Option with Autoload Disabled

By default, options are autoloaded. But you can disable this.

add_option( 'large_dataset', 'a_very_large_string', '', 'no' ); // Adds an option 'large_dataset' with autoload disabled

Update an Option

The add_option() function will not update existing options. To do that, you should use the update_option() function.

update_option( 'site_theme_color', 'red' ); // Updates the 'site_theme_color' option value to 'red'

Check if an Option Exists

Before adding an option, you might want to check if it already exists using the get_option() function.

if( false === get_option( 'my_custom_option' ) ) {
  add_option( 'my_custom_option', 'my_value' ); // Adds the 'my_custom_option' only if it does not exist
}