WordPress - 如何对来自文本区域的多行文本进行清理,而不会丢失换行符?

21

如果我要对用户输入的一些元数据文本(称为“消息”)进行清理并保存,就会像这样...

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 codex, sanitize_text_field() 函数会去除换行符。那么我如何对用户输入的文本进行清理而不失去他们的换行符?

5个回答

53

1
谢谢你。很遗憾没有办法更改最佳答案 - 特别是因为这个答案可能需要几年时间才能获得比所选的最佳答案更多的赞同票数。 - ban-geoengineering
2
这是大家正在寻找的答案。它应该替换其他答案。 - Henrik Petterson
1
这是真正的解决方案。 - Nathan Hangen

34

一种更优雅的解决方案:

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

如果您想要对文本字段进行消毒处理,请使用 sanitize_text_field


3
谢谢你,这不仅优雅,而且很出色。 - Ryan Burney
我不会更改用户输入,而是直接使用$wpdb->query()插入一个帖子元数据,这样可以避免WordPress对元数据输入进行无聊的净化处理,对于你的特定情况来说并不需要。 - Meglio

1
如果换行是你想保留的唯一内容,那么在调用sanitize_text_field之前和之后,你可以使用str_replace来替换"\n"。
$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_*函数。

谢谢您。您的代码有几个错误,但我明白了您的意思。这是可行的代码:$NEW_LINE = "\n"; $NEW_LINE_SUBSTITUTE = "NEWLINE-SUBSTITUTE"; update_post_meta($post_id, 'message', sanitize_text_field( str_replace($NEW_LINE, $NEW_LINE_SUBSTITUTE, $_POST['message'] )) ); echo '<textarea id="message" name="message">' . str_replace($NEW_LINE_SUBSTITUTE, $NEW_LINE, esc_textarea( get_post_meta( $post->ID, 'message', true ) ) ) . '</textarea>'; - ban-geoengineering

0

尝试了所有方法,唯一让我成功的方式是这样的:

function.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())才能正常工作。


0

我一直在尝试使用这种方法,发现文本区域中的撇号在输入时被反斜杠转义,但在输出时却没有被esc_textarea移除。

所以我最终不得不使用

stripslashes( esc_textarea( $THING ) ) 

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接