Select Page

Data sanitization is crucial in WordPress. Even this is an essential security measurement. Every data from the user’s input must be sanitized as early as possible. WordPress provides many helper functions for data sanitization you can find here. Very easy & handy function! But the real scenario may not be straightforward.

What if we need to sanitize form data having a large set of data & sanitizing one by one field may feel cumbersome? So, to get rid of this we can create a helper function that can loop through all the array elements and sanitize them one by one for us. But a little gotcha here! Of course, we may not use the same sanitization function for each field. For example: for email sanitization, we need to use sanitize_email while for the post we will use wp_kses_post.

So let’s fix the above-discussed problem:

/**
 * Sanitize array, single or multi dimensional array
 * Explicitly setup how should a value sanitize by the
 * sanitize function.
 *
 * @see available sanitize func
 * https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/
 *
 * @param array $input array to sanitize.
 * @param array $sanitize_mapping single dimensional map key value
 * pair to set up sanitization process. Key name should by inside
 * input array and the value will be callable func.
 * For ex: [key1 => sanitize_email, key2 => wp_kses_post ]
 *
 * If key not passed then default sanitize_text_field will be used.
 *
 * @return array
 */
function sanitize_array( array $input, array $sanitize_mapping = array() ):array {
	$array = array();

	if ( is_array( $input ) && count( $input ) ) {
		foreach ( $input as $key => $value ) {
			if ( is_array( $value ) ) {
				$array[ $key ] = sanitize_array( $value );
			} else {
				$key = sanitize_text_field( $key );

				// If mapping exists then use callback.
				if ( isset( $sanitize_mapping[ $key ] ) ) {
					$callback = $sanitize_mapping[ $key ];
					$value    = call_user_func( $callback, wp_unslash( $value ) );
				} else {
					$value = sanitize_text_field( wp_unslash( $value ) );
				}
				$array[ $key ] = $value;
			}
		}
	}
	return is_array( $array ) && count( $array ) ? $array : array();
}

So the sanitize_array function is a cursive function that can do sanitization each array value using respective sanitization functions.

The first argument on the function is an array that could be single or multi-dimensional. And, the second argument is that is optional but we can tell which array element should use which function. A simple key value pair, where the key is the key name from the array and the value is the respective sanitization function name that we want to use for a particular value.

Hope you enjoyed it 😀