Function and usage of add_option() in wordpress


Answers ( 1 )


    The add_option() function in WordPress is a utility for adding new options (settings) to the WordPress database. Here's a detailed explanation of its function and usage:


    • Adds a new option.


    • Automatic Serialization: The add_option() function automatically serializes values that need serialization before inserting them into the database. Serialization is the process of converting a data structure into a format that can be easily stored or transmitted.
    • No Resource Serialization: It's important to note that resources cannot be serialized or added as an option.
    • Delayed Value Assignment: Options can be created without initial values and updated later.
    • No Overwrite of Existing Options: This function checks to ensure the option being added is not already present. It also ensures that you don't accidentally add an option with a name that is protected within WordPress.


    1. $option (string, required):
      • The name of the option you want to add. This name should not be SQL-escaped.
    2. $value (mixed, optional):
      • The value for the option. This can be any serializable data type. Non-scalar values (like arrays or objects) must be serializable. This value should not be SQL-escaped. Defaults to an empty string.
    3. $deprecated (string, optional):
      • Previously used for a description but is no longer used. It's a legacy parameter and should typically be left as an empty string. Defaults to an empty string.
    4. $autoload (string|bool, optional):
      • Determines whether the option should be loaded automatically when WordPress starts up. Acceptable values are:
        • 'yes' or true: Enables autoloading. Recommended for options frequently accessed.
        • 'no' or false: Disables autoloading. Advised for options accessed only occasionally or on specific parts of your site. Defaults to 'yes'.


    • Boolean (bool):
      • Returns true if the option was successfully added.
      • Returns false if the option could not be added (e.g., if it already exists or is a protected option).

    Sample Usage:

    // Example: Adding a new option with autoloading enabled
    add_option('my_custom_option', 'my_value');
    // Example: Adding an option with a complex value (array) and autoloading disabled
    add_option('my_complex_option', array('key1' => 'value1', 'key2' => 'value2'), '', 'no');

    In these examples, 'my_custom_option' and 'my_complex_option' are the names of the new options. The first example adds a simple string value and defaults to autoloading. The second example adds a more complex value (an array) and specifies not to autoload the option.

Leave an answer