WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/add option

Description

A safe way of adding a named option/value pair to the options database table. It does nothing if the option already exists. After the option is saved, it can be accessed with get_option(), changed with update_option(), and deleted with delete_option().

You do not need to serialize values. If the value needs to be serialized, then it will be serialized before it is inserted into the database. You can create options without values and then add values later.

Calling add_option first checks whether the option has already been added, and returns false if an option with the same name exists. Next, it checks to make sure the option name is not one of the protected names alloptions or notoptions, and dies with an error message if attempting to overwrite a protected option. If the option name is not protected, and does not already exist, the option will be created.

Note: add_option uses get_option to determine whether the option already exists, and since get_option returns false as the default value, if you set an option to false in the database (e.g. via update_option($option_name, false)), then a subsequent call to add_option will change the value, because it will seem to add_option that the option does not exist.

vs. update_option()

If you are trying to ensure that a given option is created, use update_option() instead, which bypasses the option name check and updates the option with the desired value whether or not it exists.

Until version 4.2 (trac), you could not specify autoload='no' if you use update_option(). If you need to specify autoload='no', and you are not sure whether the option already exists, then call delete_option() first before calling add_option().

Usage

<?php add_option$option$value$deprecated$autoload ); ?>

Parameters

$option
(string) (required) Name of the option to be added. Must not exceed 64 characters. Use underscores to separate words, and do not use uppercase—this is going to be placed into the database.
Default: None
$value
(mixed) (optional) Value for this option name. Limited to 2^32 bytes of data
Default: Empty string
$deprecated
(string) (optional) Deprecated in WordPress Version 2.3.
Default: Empty string
$autoload
(string) (optional) Should this option be automatically loaded by the function wp_load_alloptions() (puts options into object cache on each page load)? Valid values: yes or no.
Default: yes

Return Value

(boolean) 
False if option was not added and true if option was added

Example

<?php add_option( 'myhack_extraction_length', '255', '', 'yes' ); ?>

Change Log

Since: 1.0.0

Source File

add_option() is located in wp-includes/option.php.

Related

See also index of Function Reference and index of Template Tags.