I'm using the Settings API to save the settings of my plugin. I want a positive integer value from the settings field.

register_setting( $option_group, $option_name . '_number', 'sanitize_number_callback' );

function sanitize_number_callback( $value ) {

    $filtered = sanitize_text_field( $value );

    if ( preg_match('/\A[1-9]\d*\Z/', $filtered) ) {
        return $filtered;
        $type = 'error';
        $message = 'Number must be a positive integer';

            esc_attr( 'settings_updated' ),

Now if the user enters a non integer value and tries to save the settings, the error is shown and an empty value is saved into the database overwriting the previously saved value, because there is no return statement when condition is false. And the field value is also made empty.

Now if I return the sanitized value which is not valid, then it's still saved in the database!

I don't know how it makes sense that an error has been shown and the settings are still saved! Quite Strange!

What I want:

  1. Sanitize and validate the $value
  2. Prevent the settings from being saved if invalid.
  3. Retain the entered value in the form field

Is there any workaround for this?

1 Answer 1


You'd do it something like this:

function sanitize_number_callback ($input){

    if( !preg_match( '/...regex for valid here.../', $input ) ){
            esc_attr( 'my_option' ), //becomes part of id attribute of error message
            __( 'Number must be a positive integer', 'wordpress' ), //default text zone
        $input = get_option( 'my_option' ); //keep old value

    return $input;

Basically, if validation fails, you return the old saved value. Your validation is completely constraining the input values so no need to sanitize as well.

I don't know how you'd hold the incorrect value in the form field if validation failed. As far as I can see, the settings API doesn't allow for it directly. Someone else may be able to provide a solution?

  • Yes, that's how I retain the old saved value.Yes there is no way in Settings API to retain the incorrect value. Commented May 3, 2017 at 7:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.