函数文档

wp_unique_id()

💡 云策文档标注

概述

wp_unique_id() 是 WordPress 中用于生成唯一 ID 的函数,基于 PHP 静态变量实现递增计数,返回带可选前缀的字符串 ID。

关键要点

  • 函数实现参考 Underscore 的 uniqueId 方法,通过静态计数器确保在 PHP 进程生命周期内唯一
  • 接受一个可选字符串参数 $prefix 作为 ID 前缀,返回格式为前缀加递增数字的字符串
  • 主要用于内部功能,如 WP_Duotone::render_duotone_support() 中生成 CSS 样式和 SVG 的唯一标识

代码示例

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

注意事项

生成的 ID 仅在当前 PHP 进程内唯一,不保证全局唯一性;自 WordPress 5.0.3 版本引入。


📄 原文内容

Gets unique ID.

Description

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.

Parameters

$prefixstringrequired
Prefix for the returned ID.

Return

string Unique ID.

Source

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

Changelog

Version Description
5.0.3 Introduced.