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 );
}
}
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 );
}
}
Share
Improve this question
asked Jun 15, 2019 at 1:49
colbyalbocolbyalbo
861 silver badge9 bronze badges
2 Answers
Reset to default 0It'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.
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);
...
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745400380a4626072.html
评论列表(0条)