Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 459
ban-geoengineering Avatar asked Dec 07 '13 17:12

ban-geoengineering


2 Answers

Since Wordpress 4.7.0

Use sanitize_textarea_field instead of sanitize_text_field

like image 136
NME New Media Entertainment Avatar answered Oct 16 '22 07:10

NME New Media Entertainment


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.

like image 38
mpatek Avatar answered Oct 16 '22 05:10

mpatek