wp_unique_prefixed_id( string $prefix = '' ): string

Generates an incremental ID that is independent per each different prefix.

Description

It is similar to wp_unique_id, but each prefix has its own internal ID counter to make each prefix independent from each other. The ID starts at 1 and increments on each call. The returned value is not universally unique, but it is unique across the life of the PHP process and it’s stable per prefix.

Parameters

$prefixstringoptional
Prefix for the returned ID.

Default:''

Return

string Incremental ID per prefix.

Source

 * 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.
 *
 * @since 5.0.3
 *
 * @param string $prefix Prefix for the returned ID.
 * @return string Unique ID.
 */
function wp_unique_id( $prefix = '' ) {
	static $id_counter = 0;
	return $prefix . (string) ++$id_counter;
}

/**
 * Generates an incremental ID that is independent per each different prefix.

Changelog

VersionDescription
6.4.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    One might ask: what is the difference between wp_unique_id( 'my-prefix' ); and wp_prefixed_unique_id( 'my-prefix' ), because they both increment a counter.

    wp_prefixed_unique_id( 'my-prefix' ); increments based on the matching of the actual prefix string: my-prefix.

    wp_unique_id() will increment regardless of whether you provide a string or not, and it will not attempt to match the string.

    So, another plugin might call wp_unique_id() on the page lifecycle and you call later on wp_unique_id( 'my-prefix' ). Your counter will be 2.

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