函数文档

wp_unslash()

💡 云策文档标注

概述

wp_unslash() 是 WordPress 核心函数,用于从字符串或数组中递归移除反斜杠。它主要用于处理传递给核心 API 的数据,确保数据符合预期格式。

关键要点

  • 函数接受字符串或数组作为参数,递归移除反斜杠,返回相同类型的未转义值
  • 内部调用 stripslashes_deep() 实现功能,适用于处理 $_POST、$_GET 等可能被转义的数据
  • 在 WordPress 3.6.0 版本引入,广泛用于各种核心功能如 AJAX 处理、自定义器、用户输入清理等场景

代码示例

$arr = array(
    "Is your name O'reilly?",
    "Person's Assets"
);
$arr = wp_unslash( $arr );
// 输出:array("Is your name O'reilly?", "Person's Assets")

注意事项

  • 主要用于修复 WordPress 自动添加的反斜杠转义,常见于表单提交和 Cookie 处理
  • 开发者应注意数据来源,避免不必要的转义移除操作

📄 原文内容

Removes slashes from a string or recursively removes slashes from strings within an array.

Description

This should be used to remove slashes from data passed to core API that expects data to be unslashed.

Parameters

$valuestring|arrayrequired
String or array of data to unslash.

Return

string|array Unslashed $value, in the same type as supplied.

Source

function wp_unslash( $value ) {
	return stripslashes_deep( $value );
}

Changelog

Version Description
3.6.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Example

    This function can be used in replacement of stripslashes_deep() . As it is a recursive function, when an array is given, it will remove slashes in all sub-arrays too.

    $arr = array(
    	"Is your name O'reilly?",
    	"Person's Assets"
    );
    
    $arr = wp_unslash( $arr );
    /*
     Outputs: 
     array(
          "Is your name O'reilly?",
          "Person's Assets"
     );
    */

  2. Skip to note 5 content

    This function was called when we try to read $_COOKIES:

    $viewed_products = ! empty( $_COOKIE['woocommerce_recently_viewed'] ) ? (array) explode( '|', wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ) ) : array(); // @codingStandardsIgnoreLine
    $viewed_products = array_reverse( array_filter( array_map( 'absint', $viewed_products ) ) );

  3. Skip to note 6 content

    It’s unfortunate that we have to invoke this function to undo the garbling of the input values performed by WordPress itself. The bug reports for fixing the problem have been thrashing about for years, and it’s unclear whether the problem will ever be fixed, or how. In the meantime here’s one way to deal with it, using a technique which should survive without having to revisit code in the event that WP ever bites the bullet and removes the unwanted escaping.

    • add a hidden field with an apostrophe but no backslash in the value (e.g., “foo’bar”)
    • when processing the posted form, test that value as returned in $_POST
    • if the value contains a backslash character, make a copy of $_POST using wp_unslash()
    • otherwise, WP has abandoned the practice of escaping the posted values, so no unslashing is needed