serialize_block_attributes()
云策文档标注
概述
serialize_block_attributes() 函数用于将属性数组转换为序列化字符串格式,以便嵌入到文章内容中。它通过 JSON 编码和字符转义确保与块编辑器中的 JavaScript 函数输出一致。
关键要点
- 输入参数为 $block_attributes(数组),输出为序列化后的字符串。
- 使用 wp_json_encode() 进行 JSON 编码,并应用特定字符转义以防止干扰 HTML 注释。
- 必须与块编辑器中的 serializeAttributes JavaScript 函数保持同步,以确保 PHP 和 JavaScript 操作的一致性。
- 函数在 WordPress 5.3.1 版本中引入。
代码示例
function serialize_block_attributes( $block_attributes ) {
$encoded_attributes = wp_json_encode( $block_attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
return strtr(
$encoded_attributes,
array(
'\' => 'u005c',
'--' => 'u002du002d',
' ' => 'u003c',
'>' => 'u003e',
'&' => 'u0026',
'"' => 'u0022',
)
);
}注意事项
此函数主要用于内部处理,开发者应确保属性数组格式正确,以避免序列化错误。
原文内容
Given an array of attributes, returns a string in the serialized attributes format prepared for post content.
Description
The serialized result is a JSON-encoded string, with unicode escape sequence substitution for characters which might otherwise interfere with embedding the result in an HTML comment.
This function must produce output that remains in sync with the output of the serializeAttributes JavaScript function in the block editor in order to ensure consistent operation between PHP and JavaScript.
Parameters
$block_attributesarrayrequired-
Attributes object.
Source
function serialize_block_attributes( $block_attributes ) {
$encoded_attributes = wp_json_encode( $block_attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
return strtr(
$encoded_attributes,
array(
'\\' => '\u005c',
'--' => '\u002d\u002d',
'<' => '\u003c',
'>' => '\u003e',
'&' => '\u0026',
'\"' => '\u0022',
)
);
}
Changelog
| Version | Description |
|---|---|
| 5.3.1 | Introduced. |