Validate an option array

We use the default WordPress register_setting() function to validate theme options. This call, for example:

register_setting( 'options-group', 'option1', 'intval' );

Will validate whether or not $option1 is an integer.

What can I use to pass an array of options to validate each member of the array?

For example:

$options = array(
    'options1' => 4,              // intval
    'options2' => '127.0.0.1',    // IP address
    'options3' => 'test@test.com' // Email address
);

2 Answers
2

What you need to do is build your own data validation function. Ozh wrote a great tutorial about this earlier, but here’s the gist of it …

Assume your options array is called $my_options and it contains three fields, 'text', 'age', and 'isauthorized'.

You would still register it the same way:

register_setting( 'my_setting', 'my_options', 'my_validation_function' );

But you see how we used a custom callback for the third parameter? Now we just need to define that custom function:

function my_validation_function( $input ) {
    // Validate age as an integer
    $input['age'] = intval( $input['age'] );

    // Strip HTML tags from text to make it safe
    $input['text'] = wp_filter_nohtml_kses( $input['text'] );

    // Make sure isauthorized is only true or false (0 or 1)
    $input['isauthorized'] = ( $input['isauthorized'] == 1 ? 1 : 0 );

    return $input;
}

Alternatively

If you want to make your validation functions a bit more flexible, you can use WordPress’ built-in filters to avoid having to repeat your code. You still register your validation the same way:

register_setting( 'my_setting', 'my_options', 'my_validation_function' );

But instead of checking each element of your array inside the validation function, you iterate through the array and delegate to filters:

function my_validation_function( $input ) {
    foreach( $input as $key => $value ) {
        $input[$key] = apply_filters( 'my_validation_' . $key, $value );
    }

    return $input
}

Now you can hook in whatever validation logic you need:

add_filter( 'my_validation_age', 'validate_numeric' );
function validate_numeric( $numeric ) {
    return intval( $numeric );
}

add_filter( 'my_validation_text', 'validate_text' );
function validate_text( $text ) {
    return wp_filter_nohtml_kses( $text );
}

add_filter( 'my_validation_isauthorized', 'validate_bool' );
function validate_bool( $bool ) {
    return $bool == 1 ? 1 : 0;
}

If you don’t add a filter for one of your options, then the value of the option will remain unchanged. Filters are also the way you want to go with functions that return content, and you can add as many as you want … or attach your filters to any fields.

Let’s say you had two numeric fields in your array – age and numberChildren. Instead of creating an extra validation function that can handle the numberChildren field, you just add it to the filter:

add_filter( 'my_validation_numberChildren', 'validate_numeric' );

Leave a Comment