Using WordPress ‘filter_default_option()’ PHP function

The filter_default_option() WordPress PHP function filters the default value for a given option. This function comes into play for settings that register a default setting in register_setting().

Usage

Here’s a generic example of using the filter_default_option() function:

add_filter( 'default_option_my_option', 'my_option_default', 10, 3 );

function my_option_default( $default_value, $option, $passed_default ) {
    if ( $passed_default ) {
        return $default_value;
    } else {
        return 'My Default Value';
    }
}

This code adds a filter to the default_option_my_option hook. The filter function my_option_default will return the passed default value if one exists, otherwise it will return ‘My Default Value’.

Parameters

  • $default_value (mixed): The existing default value to return.
  • $option (string): The name of the option.
  • $passed_default (bool): A boolean indicating if get_option() was passed a default value.

More information

See WordPress Developer Resources: filter_default_option()
This function is typically used in conjunction with register_setting() and get_option().

Examples

Adding a Default Value to a New Option

add_filter( 'default_option_my_new_option', 'my_new_option_default', 10, 3 );

function my_new_option_default( $default_value, $option, $passed_default ) {
    return $passed_default ? $default_value : 'New Default Value';
}

This code sets ‘New Default Value’ as the default for the my_new_option setting if no default value was passed.

Change Default Value Based on Condition

add_filter( 'default_option_theme_color', 'theme_color_default', 10, 3 );

function theme_color_default( $default_value, $option, $passed_default ) {
    return ( 'dark' === get_option('site_mode') ) ? 'black' : 'white';
}

This code changes the default theme color based on the site_mode setting. If site_mode is ‘dark’, the default theme color will be ‘black’. Otherwise, it will be ‘white’.

Handling Numeric Options

add_filter( 'default_option_posts_per_page', 'posts_per_page_default', 10, 3 );

function posts_per_page_default( $default_value, $option, $passed_default ) {
    return $passed_default ? $default_value : 10;
}

In this code, if no default value was passed for posts_per_page, it will be set to 10.

Setting Default Values for Array Options

add_filter( 'default_option_theme_settings', 'theme_settings_default', 10, 3 );

function theme_settings_default( $default_value, $option, $passed_default ) {
    return $passed_default ? $default_value : array('color' => 'blue', 'font' => 'Arial');
}

For the theme_settings option, if no default value was passed, the default will be an array with ‘color’ set to ‘blue’ and ‘font’ set to ‘Arial’.