WordPress-如何在不丢失换行符的情况下从文本区域清除多行文本


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

如果我像这样清理并保存用户输入的一些元文本(称为"消息")。。。

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

然后检索并尝试像这样重新显示文本。。。

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

所有的断线都会丢失。

根据WordPress的代码,换行符被sance_text_field()函数去除。那么,我如何在不丢失用户换行符的情况下对用户输入的文本进行消毒呢?

自Wordpress 4.7.0 以来

使用消毒_文本区域字段而不是消毒_文本字段

一个更优雅的解决方案:

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

如果要清除文本字段,请使用sanitize_text_field

如果换行符是sanitize_text_field要删除的唯一内容,则可以在调用sanitize_text_field之前和之后仅为"'n"使用str_replace

$fake_newline = '--OMGKEEPTHISNEWLINE--'; # or some unique string
$escaped_newlines = str_replace("'n", $fake_newline, $_POST['message']);
$sanitized = sanitize_text_field($escaped_newlines);
update_post_meta($post_id, 'message', str_replace($fake_newline", "'n", $sanitized));

如果你想更多地自定义净化,你可能应该依赖WordPress提供的更细粒度的sanitize_*函数。

我自己一直在尝试使用这个方法,发现文本区域中的撇号在输入时被反斜杠转义,然后在输出时不会被esc_textarea删除。

所以我不得不使用

stripslashes( esc_textarea( $THING ) ) 

以在重新显示时成功地将它们从文本区域中删除。

尝试了一切,我唯一能做到这一点的方法是:

函数.php

wp_customize->add_section('section_id', array(
    'title' => __('custom_section', 'theme_name'),
    'priority' => 10,
    'description' => 'Custom section description',
));
$wp_customize->add_setting('custom_field', array(
    'capability' => 'edit_theme_options',
    'sanitize_callback' => 'sanitize_textarea_field',
));
$wp_customize->add_control('custom_field', array(
    'type' => 'textarea',
    'section' => 'custom_section',
    'label' => __('Custom text area with multiline brakes'),
));

显示在前面(例如footer.php)

<?php $custom_field= get_theme_mod('custom_field');
    if ($custom_field) {
        echo nl2br( esc_html( $custom_field) );
} ?>

必须使用'sanitize_callback' => 'sanitize_textarea_field'nl2br( esc_html())才能工作。

相关文章: