wp_unique_prefixed_id()
云策文档标注
概述
wp_unique_prefixed_id() 函数用于为每个不同的前缀生成独立的递增 ID,类似于 wp_unique_id(),但每个前缀拥有独立的计数器,确保 ID 在 PHP 进程生命周期内唯一且稳定。
关键要点
- 函数为每个前缀维护独立的 ID 计数器,从 1 开始递增。
- 返回的 ID 不是全局唯一,但在 PHP 进程内对同一前缀是唯一的。
- 参数 $prefix 为可选字符串,默认为空字符串,用于区分不同前缀的 ID 序列。
- 如果 $prefix 不是字符串,会触发错误并默认使用空字符串。
代码示例
function wp_unique_prefixed_id( $prefix = '' ) {
static $id_counters = array();
if ( ! is_string( $prefix ) ) {
wp_trigger_error(
__FUNCTION__,
sprintf( 'The prefix must be a string. "%s" data type given.', gettype( $prefix ) )
);
$prefix = '';
}
if ( ! isset( $id_counters[ $prefix ] ) ) {
$id_counters[ $prefix ] = 0;
}
$id = ++$id_counters[ $prefix ];
return $prefix . (string) $id;
}注意事项
- 与 wp_unique_id() 不同,wp_unique_prefixed_id() 基于前缀字符串匹配来递增计数器,而 wp_unique_id() 无论是否提供前缀都会递增全局计数器。
- 例如,如果另一个插件调用 wp_unique_id(),然后你调用 wp_unique_id('my-prefix'),你的计数器会从 2 开始,而 wp_unique_prefixed_id('my-prefix') 会为 'my-prefix' 前缀独立计数。
原文内容
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 empty string.
Source
function wp_unique_prefixed_id( $prefix = '' ) {
static $id_counters = array();
if ( ! is_string( $prefix ) ) {
wp_trigger_error(
__FUNCTION__,
sprintf( 'The prefix must be a string. "%s" data type given.', gettype( $prefix ) )
);
$prefix = '';
}
if ( ! isset( $id_counters[ $prefix ] ) ) {
$id_counters[ $prefix ] = 0;
}
$id = ++$id_counters[ $prefix ];
return $prefix . (string) $id;
}
Changelog
| Version | Description |
|---|---|
| 6.4.0 | Introduced. |
Skip to note 2 content
Damon Cook
One might ask: 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' );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 onwp_unique_id( 'my-prefix' ). Your counter will be2.wp_unique_prefixed_id()and notwp_prefixed_unique_id()in all of my examples above. 🤦🏼♂️