avatar
2 minutes read

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

Assuming I disinfect and save some meta message (called 'message') entered by the client like this...

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

..and afterward recover and endeavor to re-show the text like this...

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

Where:

..all the line breaks get lost.

As per the WordPress codex, the line breaks are being stripped out by the sanitize_text_field() capability. So how might I clean the text entered by the client without losing their line breaks?

Solutions

update_post_meta(
    $post_id,
    'message',
    implode( "\n", array_map( 'sanitize_textarea_field', explode( "\n", $_POST['message'] ) ) )
);

Use sanitize_text_field if you have any desire to clean text field.

Comments