Using WordPress ‘add_option’ PHP action

The add_option WordPress PHP action fires before an option is added to the database.

Usage

add_action('add_option', 'my_custom_function', 10, 2);

function my_custom_function($option, $value) {
  // your custom code here

  return $option;
}

Parameters

  • $option (string) – Name of the option to add.
  • $value (mixed) – Value of the option.

More information

See WordPress Developer Resources: add_option

Examples

Log option addition

Log option additions to a custom log file.

add_action('add_option', 'log_option_addition', 10, 2);

function log_option_addition($option, $value) {
  error_log("Adding option '{$option}' with value '{$value}'");
}

Validate option values

Prevent adding options with invalid values.

add_action('add_option', 'validate_option_values', 10, 2);

function validate_option_values($option, $value) {
  if ($option === 'my_custom_option' && !is_numeric($value)) {
    wp_die('Invalid value for my_custom_option');
  }
}

Send notification when option is added

Send an email notification when a specific option is added.

add_action('add_option', 'send_notification_on_option_add', 10, 2);

function send_notification_on_option_add($option, $value) {
  if ($option === 'important_option') {
    wp_mail('[email protected]', 'Important option added', "Option '{$option}' added with value '{$value}'");
  }
}

Set a default value for a new option

Automatically set a default value for a specific option when it’s added.

add_action('add_option', 'set_default_value_for_new_option', 10, 2);

function set_default_value_for_new_option($option, $value) {
  if ($option === 'custom_option' && empty($value)) {
    update_option($option, 'default_value');
  }
}

Update another option when a specific option is added.

add_action('add_option', 'update_related_options', 10, 2);

function update_related_options($option, $value) {
  if ($option === 'main_option') {
    update_option('related_option', $value);
  }
}