Using WordPress ‘pre_update_option_{$option}’ PHP filter

“pre_update_option_{$option}” is a dynamic WordPress PHP filter that allows you to modify a specific option value before it is serialized and updated in the WordPress database.

The dynamic part of the hook name ({$option}) refers to the option name.

Usage

function my_pre_update_option_option( $value, $old_value, $option ) {
    return $value;
}
add_filters( "pre_update_option_{$option}", "my_pre_update_option_option" );

Parameters

  • $value (mixed): The new, unserialized option value.
  • $old_value (mixed): The old option value.
  • $option (string): Option name.

Examples

Validate an Email Address

Scenario: You want to validate an email address before saving it as a WordPress option.

function validate_email_option( $value, $old_value, $option ) {
    if ( !is_email( $value ) ) {
        return $old_value;
    }
    return $value;
}
add_filter( 'pre_update_option_admin_email', 'validate_email_option', 10, 3 );

This code checks if the new email address is valid using the is_email() function. If it’s not valid, the old value is returned and the option remains unchanged.

Limit Post Revisions

Scenario: You want to limit the number of post revisions that can be saved.

function limit_post_revisions( $value, $old_value, $option ) {
    if ( $value > 10 ) {
        return 10;
    }
    return $value;
}
add_filter( 'pre_update_option_wp_post_revisions', 'limit_post_revisions', 10, 3 );

This code ensures that the maximum number of post revisions saved does not exceed 10.

Sanitize Custom CSS

Scenario: You want to sanitize custom CSS input before saving it to the database.

function sanitize_custom_css( $value, $old_value, $option ) {
    return wp_kses( $value, array( '\'', '\"' ) );
}
add_filter( 'pre_update_option_custom_css', 'sanitize_custom_css', 10, 3 );

This code uses the wp_kses() function to sanitize the custom CSS by removing any unwanted characters.

Ensure Positive Integer for a Custom Option

Scenario: You want to ensure that a custom option value is always a positive integer.

function enforce_positive_integer( $value, $old_value, $option ) {
    return absint( $value );
}
add_filter( 'pre_update_option_custom_option', 'enforce_positive_integer', 10, 3 );

This code ensures that the custom option value is always a positive integer by using the absint() function.

Update an Additional Option

Scenario: You want to update an additional option when a specific option is updated.

function update_additional_option( $value, $old_value, $option ) {
    update_option( 'additional_option', $value . '_suffix' );
    return $value;
}
add_filter( 'pre_update_option_main_option', 'update_additional_option', 10, 3 );

This code updates the ‘additional_option’ with the new value of ‘main_option’ concatenated with a ‘_suffix’ string.