函数文档

wp_interactivity_data_wp_context()

💡 云策文档标注

概述

wp_interactivity_data_wp_context() 是一个 WordPress 辅助函数,用于生成 data-wp-context 指令属性,通过编码上下文数组为 JSON 字符串,以便安全地用作 HTML 属性值。

关键要点

  • 函数接受一个必需的 $context 数组参数和一个可选的 $store_namespace 字符串参数。
  • 返回一个完整的 data-wp-context 指令字符串,包含 JSON 编码的上下文数据,并可选择性地添加存储命名空间。
  • 使用 wp_json_encode() 进行编码,并应用 JSON_HEX_TAG、JSON_HEX_APOS、JSON_HEX_QUOT 和 JSON_HEX_AMP 标志以确保 HTML 安全性。

代码示例

echo wp_interactivity_data_wp_context( array( 'isOpen' => true, 'count' => 0 ) );

注意事项

  • 该函数在 WordPress 6.5.0 版本中引入。
  • 如果 $context 数组为空,函数将输出 '{}' 作为默认 JSON 值。

📄 原文内容

Generates a data-wp-context directive attribute by encoding a context array.

Description

This helper function simplifies the creation of data-wp-context directives by providing a way to pass an array of data, which encodes into a JSON string safe for direct use as a HTML attribute value.

Example:

<div <?php echo wp_interactivity_data_wp_context( array( 'isOpen' => true, 'count' => 0 ) ); ?>>

Parameters

$contextarrayrequired
The array of context data to encode.
$store_namespacestringoptional
The unique store namespace identifier.

Return

string A complete data-wp-context directive with a JSON encoded value representing the context array and the store namespace if specified.

Source

function wp_interactivity_data_wp_context( array $context, string $store_namespace = '' ): string {
	return 'data-wp-context='' .
		( $store_namespace ? $store_namespace . '::' : '' ) .
		( empty( $context ) ? '{}' : wp_json_encode( $context, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP ) ) .
		''';
}

Changelog

VersionDescription
6.5.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.