Using WordPress ‘add_option_update_handler()’ PHP function

The add_option_update_handler() WordPress PHP function registers a setting and its sanitization callback. This function is closely related to register_setting(). It allows you to register a settings group name, which should match an allowed option key name. Default key names include ‘general’, ‘discussion’, ‘media’, ‘reading’, ‘writing’, and ‘options’.

Usage

add_option_update_handler('my_option_group', 'my_option_name', 'my_sanitize_callback');

In this example, we’re setting up a new option named ‘my_option_name’ in the ‘my_option_group’ group, and we’re using ‘my_sanitize_callback’ as the function to sanitize the value of the option.

Parameters

  • $option_group (string, required): A settings group name. Should correspond to an allowed option key name.
  • $option_name (string, required): The name of an option to sanitize and save.
  • $sanitize_callback (callable, optional): A callback function that sanitizes the option’s value.

More Information

See WordPress Developer Resources: add_option_update_handler
This function is a part of WordPress core and can be found in the wp-includes/option.php file.

Examples

In these examples, ‘theme_options’ is the settings group name, ‘my_theme_option’ is the option name to sanitize and save, and the third parameter is the callback function that sanitizes the option’s value. The sanitize function is optional. If it’s not provided, WordPress will use a default sanitize function.

Register a New Option

This code registers a new option with the name ‘my_theme_option’ in the ‘theme_options’ group.

add_option_update_handler('theme_options', 'my_theme_option', 'sanitize_text_field');

Use a Custom Sanitize Function

This code shows how to use a custom sanitize function for your option.

function my_sanitize_function($input) {
  // sanitize the input before saving
  $output = sanitize_text_field($input);
  return $output;
}

add_option_update_handler('theme_options', 'my_theme_option', 'my_sanitize_function');

Update an Option

After registering an option, you can update it using update_option() function.

add_option_update_handler('theme_options', 'my_theme_option', 'sanitize_text_field');
update_option('my_theme_option', 'My new option value');

Retrieve an Option

You can retrieve the saved option value using the get_option() function.

add_option_update_handler('theme_options', 'my_theme_option', 'sanitize_text_field');
update_option('my_theme_option', 'My new option value');

// get the option value
$option_value = get_option('my_theme_option');

Remove an Option

You can remove the option you’ve registered using the delete_option() function.

add_option_update_handler('theme_options', 'my_theme_option', 'sanitize_text_field');
delete_option('my_theme_option');