diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index e2f3f0751f..f3070315f6 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -6167,6 +6167,26 @@ function wp_is_uuid( $uuid, $version = null ) { return (bool) preg_match( $regex, $uuid ); } +/** + * Get 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 4.9.9 + * + * @staticvar int $id_counter + * + * @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; +} + /** * Get last changed date for the specified cache group. * diff --git a/tests/phpunit/tests/functions.php b/tests/phpunit/tests/functions.php index d6d5d066e0..2557f1f92a 100644 --- a/tests/phpunit/tests/functions.php +++ b/tests/phpunit/tests/functions.php @@ -1117,6 +1117,34 @@ class Tests_Functions extends WP_UnitTestCase { } } + /** + * Tests wp_unique_id(). + * + * @covers ::wp_unique_id + * @ticket 44883 + */ + function test_wp_unique_id() { + + // Test without prefix. + $ids = array(); + for ( $i = 0; $i < 20; $i += 1 ) { + $id = wp_unique_id(); + $this->assertInternalType( 'string', $id ); + $this->assertTrue( is_numeric( $id ) ); + $ids[] = $id; + } + $this->assertEquals( $ids, array_unique( $ids ) ); + + // Test with prefix. + $ids = array(); + for ( $i = 0; $i < 20; $i += 1 ) { + $id = wp_unique_id( 'foo-' ); + $this->assertRegExp( '/^foo-\d+$/', $id ); + $ids[] = $id; + } + $this->assertEquals( $ids, array_unique( $ids ) ); + } + /** * @ticket 40017 * @dataProvider _wp_get_image_mime