WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to know how to perform a proper validation with the register_setting() callback function.

Here is a sample part of my code I want to work with:

register_setting( 'wpPart_options', 'wpPart_options', array( &$this, 'wpPartValidate_settings' ) );

$this is an array of objects.

And here is the content of my wpPartValidate_settings(); function.

public function wpPartValidate_settings( $input ) {

   $options = get_option( 'wpPart_options' );
   if ( check_admin_referer( 'wpPart_nonce_field', 'wpPart_nonce_verify_adm' ) ) {
      return $input;


Since $input is an array, how can I perfom a proper validation on every input that comes to the validating function?

I would like, for example, to perform a strlen() check on a text field :

if ( strlen( $input ) != 20 )
   add_settings_error( 'wpPart_options', 'textField', __( 'TextField incomplete.', 'wpPart' ) , 'error' );
share|improve this question
Are you asking how to iterate over an array in PHP? If so then simple foreach should help you out. – montrealist Mar 7 '13 at 19:40
In fact I was asking if validating the inputs this way is the best practice and if not how to do it properly. – LittleFinger Mar 7 '13 at 23:08
up vote 1 down vote accepted

Personally I'd do it the same way, since it seems to be the only point where you can examine user input and validate it.

Also, heavily borrowing from code sample in this excellent article:

function wpPartValidate_settings( $input ) {
   if ( check_admin_referer( 'wpPart_nonce_field', 'wpPart_nonce_verify_adm' ) ) {

    // Create our array for storing the validated options
    $output = array();

    foreach( $input as $key => $value ) {

      // Check to see if the current option has a value. If so, process it.
      if( isset( $input[$key] ) ) {

        // Strip all HTML and PHP tags and properly handle quoted strings
        $output[$key] = strip_tags( stripslashes( $input[ $key ] ) );

      } // end if
    } // end foreach
  } // end if
  // Return the array processing any additional functions filtered by this action
  return apply_filters( 'wpPartValidate_settings', $output, $input );

My favourite part is the apply_filters call at the end. Now that's best practice!

share|improve this answer
Thanks for your detailed answer :) – LittleFinger Mar 8 '13 at 4:25

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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