WordPress - How to sanitize multi-line text from a textarea without losing line breaks?
A more elegant solution:
update_post_meta( $post_id, 'message', implode( "\n", array_map( 'sanitize_textarea_field', explode( "\n", $_POST['message'] ) ) ));
Use sanitize_text_field
if you want to sanitize text field.
If line breaks are the only thing sanitize_text_field
is removing that you want to keep, you could just str_replace
for "\n"
before and after calling sanitize_text_field
.
$fake_newline = '--OMGKEEPTHISNEWLINE--'; # or some unique string$escaped_newlines = str_replace("\n", $fake_newline, $_POST['message']);$sanitized = sanitize_text_field($escaped_newlines);update_post_meta($post_id, 'message', str_replace($fake_newline", "\n", $sanitized));
If you want to customize sanitization more, you should probably rely on more fine-grained sanitize_*
functions provided by WordPress.