1

I am working on an options panel for a plugin. And have an array being posted and updated to the options table. I am using the array_map() function to iterate over the array with sanitize_text_fields()

Is this an optimal way to do this?

 if( ! empty( $_POST['my_array'] ) ) {
            foreach( $_POST['my_array'] as $value ) {
                $value = array_map( 'sanitize_text_field', $value );
                update_option( 'my_option_value', $value );
            }
        } 
1

It's probably not a great idea. Firstly, if you've got other field types then you should probably use more appropriate functions. For example, textarea fields should be sanitised with sanitize_textarea_field(), and color pickers should be sanitized with sanitize_hex_color().

You should also consider that $_POST likely also contains fields that you don't want to save, such as the hidden inputs that power the Settings API: option_page, action _wpnonce, and _wp_http_referer.

Lastly, it means that your function essentially accepts all input and will add it to the database. While sanitising and escaping the inputs means they can't do too much damage, you're still not coding defensively. Ideally you'd whitelist the inputs you expect to be submitted, and only submit those.

However, you shouldn't need to handle the $_POST at all when properly using the Settings or Customisation APIs, which suggests you're not building this options panel correctly. When properly using the either of these APIs, the sanitisation function can be specified when registering the setting, and no manipulation of the submission should be necessary.

  • Thanks for the guidance, i'll research the settings api further. – colbyalbo Jun 15 at 18:00
1

I think you are in the right path. What you can do to improve is:

Separate the logic in functions to increase readability or do a good commenting what you are doing. E.g.:

... 

function mytheme_sanitize_fields($fields){

   foreach($fields as $field){
      mytheme_sanitize_field($field);
   }

}


function mytheme_sanitize_field($field){
      if( is_array($field){
           $value = array_map( 'sanitize_text_field', $field );

      }
      else{

           $value = sanitize_text_field($field);
      }

      update_option('yourkey', $value);

...

}


...


mytheme_sanitize_fields($_POST);      

...






}

  • 1
    Thanks for the feedback! – colbyalbo Jun 15 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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