wp_unique_id()
Gets unique ID.
This is a PHP implementation of Underscore's uniqueId method. A static variable contains an integer that is incremented with each call. This number is returned with the optional prefix. As such the returned value is not universally unique, but it is unique across the life of the PHP process.
No Hooks.
Return
String
. Unique ID.
Usage
wp_unique_id( $prefix );
- $prefix(string)
- Prefix for the returned ID.
Default: ''
Examples
#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
#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() wp unique id code WP 6.7.1
function wp_unique_id( $prefix = '' ) { static $id_counter = 0; return $prefix . (string) ++$id_counter; }