wp_unique_id_from_values()
Creates a short identifier from an array's structure and values.
Converts the array to JSON, calculates an MD5 hash, and uses its first 8 characters. Identical arrays create identical identifiers. The order of elements and keys affects the result.
The identifier does not guarantee absolute uniqueness because the hash is shortened to 8 characters. Do not use it as a secret token or where collisions are unacceptable.
Use wp_unique_id() when every call must create a new identifier regardless of the data passed.
No Hooks.
Returns
string.
string- an 8-character hash with the specified prefix.
Usage
wp_unique_id_from_values( $data, $prefix ): string;
- $data(array) (required)
Data from which to create the identifier.
The array must not be empty. When an empty array is passed, WordPress triggers a
_doing_it_wrong()notice but continues execution and creates an identifier.- $prefix(string)
- A prefix added before the hash. The prefix is not part of the hash calculation.
Default:''
Examples
#1 Create a CSS class from settings
An identical set of settings always creates the same class name.
$layout = [ 'layout' => 'grid', 'columns' => 3, 'gap' => '24px', ]; $class_name = wp_unique_id_from_values( $layout, 'layout-' ); printf( '<div class="%s">Content</div>', esc_attr( $class_name ) );
Changelog
| Since 6.8.0 | Introduced. |
wp_unique_id_from_values() wp unique id from values code WP 7.1.1
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;
}