urlencode_deep()
云策文档标注
概述
urlencode_deep() 是一个 WordPress 函数,用于递归遍历数组、对象或标量值,并对所有值进行 URL 编码,以便在 URL 中使用。它基于 map_deep() 函数实现,简化了深层数据结构的编码过程。
关键要点
- 函数递归处理数组、对象或标量值,应用 urlencode 函数进行编码
- 参数 $value 为必需,可以是数组或字符串,返回编码后的值
- 常用于 REST API 控制器(如 WP_REST_Posts_Controller)和 URL 构建函数(如 add_query_arg)中,确保 URL 参数安全
- 自 WordPress 2.2.0 版本引入,是核心功能的一部分
代码示例
// 字符串编码示例
echo urlencode_deep( 'foo bar' );
// 输出: foo+bar
// 数组编码示例
$data = urlencode_deep( array( 'foo' => 'bar long text', 'key1' => 'value1' ) );
// $data 输出: array( 'foo' => 'bar+long+text', 'key1' => 'value1' )
// 与 add_query_arg 结合使用示例
echo add_query_arg( 'key', urlencode_deep( 'long value' ), 'http://example.com/' );
// 输出: http://example.com/?key=long+value注意事项
- 函数自动将字符串中的空格转换为加号(+),这是 URL 编码的标准行为
- 如果不使用 urlencode_deep,直接传递包含空格的字符串到 URL 可能导致格式错误或安全问题
- 适用于需要批量编码嵌套数据结构(如多维数组)的场景,提高代码效率
原文内容
Navigates through an array, object, or scalar, and encodes the values to be used in a URL.
Parameters
$valuemixedrequired-
The array or string to be encoded.
Source
function urlencode_deep( $value ) {
return map_deep( $value, 'urlencode' );
}
Changelog
| Version | Description |
|---|---|
| 2.2.0 | Introduced. |
Skip to note 2 content
Razon Komar Pal
Here is an example for string:
echo urlencode_deep( 'foo bar' ); // Output will be: foo+barHere is an example for array:
$data = urlencode_deep( array( 'foo' => 'bar long text', 'key1' => 'value1' ) ); // Output will be for $data: array( 'foo' => 'bar+long+text', 'key1' => 'value1' )Here is a use case for multi word string as url parameter:
echo add_query_arg( 'key', urlencode_deep( 'long value' ), 'http://example.com/' ); // Output will be: <a href="http://example.com/?key=long+value" rel="nofollow ugc">http://example.com/?key=long+value</a>Here is a use case for an array multi word string as url parameter:
$params = array( 'key1' => 'value1 long text', 'key2' => 'value2', ); echo add_query_arg( urlencode_deep( $params ), 'http://example.com/?' ); // Output will be: <a href="http://example.com/?key1=value1+long+text&key2=value2" rel="nofollow ugc">http://example.com/?key1=value1+long+text&key2;=value2</a>It’s making spaces between word, if string has space:
echo add_query_arg( 'key', 'long value', 'http://example.com/' ); // Output will be: <a href="http://example.com/?key=long" rel="nofollow ugc">http://example.com/?key=long</a> value