Wordpress - wordpress sanitize array?
Here's a way to do it with PHP's array map function:
// Good idea to make sure things are set before using them
$tags = isset( $_POST['tags'] ) ? (array) $_POST['tags'] : array();
// Any of the WordPress data sanitization functions can be used here
$tags = array_map( 'esc_attr', $tags );
I needed a recursive sanitation, so here's my solution:
/**
* Recursive sanitation for an array
*
* @param $array
*
* @return mixed
*/
function recursive_sanitize_text_field($array) {
foreach ( $array as $key => &$value ) {
if ( is_array( $value ) ) {
$value = recursive_sanitize_text_field($value);
}
else {
$value = sanitize_text_field( $value );
}
}
return $array;
}
If anyone is interested, I solved it like this:
$tags = $_POST['tags'];
if (count($tags) > 5){
echo 'Niet meer dan 5 tags';
$stop = true;
}
if (is_array($tags)) {
foreach ($tags as &$tag) {
$tag = esc_attr($tag);
}
unset($tag );
} else {
$tags = esc_attr($tags);
}