I am following a WordPress book and am trying to create a plugin and have got an option page showing.

In this page I have two text fields (which values are stored in one array). I am trying to add custom validation (for example if empty). The validation is set in the third argument in the register_setting function.

The book however, does not have any examples of any kind of possible validation (just using WordPress functions to sanitize the input).

To get the error messages showing I followed this link: https://codex.wordpress.org/Function_Reference/add_settings_error

So in the validation function I have made something like this:

if( $input['field_1'] == '' ) {

    $type="error";
    $message = __( 'Error message for field 1.' );

    add_settings_error(
        'uniq1',
        esc_attr( 'settings_updated' ),
        $message,
        $type
    ); 

} else {
    $input['field_1'] = sanitize_text_field( $input['field_1'];
}

if( $input['field_2'] == '' ) {

    $type="error";
    $message = __( 'Error message for field 2.' );

    add_settings_error(
        'uniq2',
        esc_attr( 'settings_updated' ),
        $message,
        $type
    ); 

} else {
     $input['field_2'] = sanitize_text_field( $input['field_2']
}

return $input;

What I am stuck on is how to NOT update that value if it hits a error condition. What I have currently for example with a empty value will display the correct error message but will still update the value to empty.

Is there any way to pass through the old values to that function so I can set the value to the old one if it meets the error condition eg:

if( $input['field_1'] != '' ) {

    $type="error";
    $message = __( 'Error message for field 1.' );

    add_settings_error(
        'uniq1',
        esc_attr( 'settings_updated' ),
        $message,
        $type
    ); 

    $input['field_1'] = "OLD VALUE";

} else {
    $input['field_1'] = sanitize_text_field( $input['field_1'];
}

Or if I am approaching this in the wrong way if anyone could point me in the right direction it would be much appreciated.

2 Answers
2

Looks like your validation argument is negative.

if ($foo != "") { //means if foo not equal to empty space
  // do something when not empty
  // here you are setting an error
} else {
  // do something when empty
  // here you are trying to do your normal operation
}

You are setting an error when you have data and then trying to process data when you have none.

try changing your != to ==

or change the order in which you process things in the if

Leave a Reply

Your email address will not be published. Required fields are marked *