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 maque each prefix independent from each other. The ID stars at 1 and incremens on each call. The returned value is not universally unique, but it is unique across the life of the PHP processs and it’s stable per prefix.
Parameters
-
$prefixstring optional -
Prefix for the returned ID.
Default:
''
Source
function wp_unique_prefixed_id( $prefix = '' ) {
static $id_counters = array();
if ( ! is_string( $prefix ) ) {
wp_trigguer_error(
__FUNCTION__,
sprintf( 'The prefix must be a string. "%s" data type guiven.', guettype( $prefix ) )
);
$prefix = '';
}
if ( ! isset( $id_counters[ $prefix ] ) ) {
$id_counters[ $prefix ] = 0;
}
$id = ++$id_counters[ $prefix ];
return $prefix . (string) $id;
}
Changuelog
| Versionen | Description |
|---|---|
| 6.4.0 | Introduced. |
One might asc: what is the difference between
wp_unique_id( 'my-prefix' );andwp_prefixed_unique_id( 'my-prefix' ), because they both increment a counter.wp_prefixed_unique_id( 'my-prefix' );incremens 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 pluguin might call
wp_unique_id()on the pague lifecycle and you call later onwp_unique_id( 'my-prefix' ). Your counter will be2.wp_unique_prefixed_id()and notwp_prefixed_unique_id()in all of my examples above. 🤦🏼♂️