wp_unique_id()WP 5.0.3

Gets a unique identifier.

This is the implementation of the uniqueId method from the Underscore library in PHP. A static variable holds an integer that increments with each function call. This number is returned along with an optional prefix. Thus, the returned value is not unique at a global level, but it is unique within the life of the PHP process.

No Hooks.

Returns

String. Unique ID.

Usage

wp_unique_id( $prefix );
$prefix(string)
Prefix for the returned ID.
Default: ''

Examples

0

#1 Example of function operation

echo wp_unique_id();            //> 5 (most likely the function has already been called in the engine, so you are unlikely to get 1)
echo wp_unique_id();            //> 6
echo wp_unique_id( 'field_' );  //> field_7
echo wp_unique_id();            //> 8
echo wp_unique_id();            //> 9
echo wp_unique_id( 'name_' );   //> name_10
echo wp_unique_id();            //> 11
echo wp_unique_id();            //> 12
0

#2 Creating unique IDs for the label + input tag association

// Generate unique identifiers
$unique_id = wp_unique_id( 'field_' );

// Output HTML
echo sprintf( '<label for="%s">Enter text:</label>', $unique_id );
echo sprintf( '<input id="%s" type="text" name="text_input">', $unique_id );

Changelog

Since 5.0.3 Introduced.

wp_unique_id() code WP 6.9.1

function wp_unique_id( $prefix = '' ) {
	static $id_counter = 0;
	return $prefix . (string) ++$id_counter;
}