Skip to content
Advertisement

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

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement