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?
Since Wordpress 4.7.0
Use sanitize_textarea_field instead of sanitize_text_field
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With