函数文档

wp_unique_id_from_values()

💡 云策文档标注

概述

wp_unique_id_from_values() 函数基于给定数组的结构和值生成唯一 ID。它通过序列化数组为 JSON 字符串并计算哈希来实现,可选添加前缀以提供上下文或分类。

关键要点

  • 函数接受一个必需参数 $data(数组)和一个可选参数 $prefix(字符串,默认为空字符串)。
  • 返回值为字符串,即生成的唯一 ID。
  • 如果 $data 为空,会触发 _doing_it_wrong() 警告。
  • 使用 wp_json_encode() 序列化数组,然后通过 md5() 生成哈希并截取前 8 个字符。

代码示例

function wp_unique_id_from_values( array $data, string $prefix = '' ): string {
    if ( empty( $data ) ) {
        _doing_it_wrong(
            __FUNCTION__,
            sprintf(
                /* translators: %s: The parameter name. */
                __( 'The %s parameter must not be empty.' ),
                '$data'
            ),
            '6.8.0'
        );
    }

    $serialized = wp_json_encode( $data );
    $hash       = substr( md5( $serialized ), 0, 8 );

    return $prefix . $hash;
}

注意事项

  • 此函数在 WordPress 6.8.0 版本中引入。
  • 相关函数包括 wp_json_encode()、__() 和 _doing_it_wrong()。

📄 原文内容

Generates a unique ID based on the structure and values of a given array.

Description

This function serializes the array into a JSON string and generates a hash that serves as a unique identifier. Optionally, a prefix can be added to the generated ID for context or categorization.

Parameters

$dataarrayrequired
The input array to generate an ID from.
$prefixstringoptional
A prefix to prepend to the generated ID. Default empty string.

Return

string The generated unique ID for the array.

Source

function wp_unique_id_from_values( array $data, string $prefix = '' ): string {
	if ( empty( $data ) ) {
		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
				/* translators: %s: The parameter name. */
				__( 'The %s parameter must not be empty.' ),
				'$data'
			),
			'6.8.0'
		);
	}

	$serialized = wp_json_encode( $data );
	$hash       = substr( md5( $serialized ), 0, 8 );

	return $prefix . $hash;
}

Changelog

Version Description
6.8.0 Introduced.