WordPress - How to sanitize multi-line text from a textarea without losing line breaks?

ban-geoengineering picture ban-geoengineering · Dec 7, 2013 · Viewed 10.9k times · Source

If I sanitize and save some meta text (called 'message') entered by the user like like this...

update_post_meta($post_id, 'message', sanitize_text_field($_POST['message']));

...and then retrieve and attempt to re-display the text like this...

echo '<textarea id="message" name="message">' . esc_textarea( get_post_meta( $post->ID, 'message', true ) ) . '</textarea>';

...all the line breaks get lost.

In accordance with the WordPress codex, the line breaks are being stripped out by the sanitize_text_field() function. So how can I sanitize the text entered by the user without losing their line breaks?

Answer

Since Wordpress 4.7.0

Use sanitize_textarea_field instead of sanitize_text_field