获取给定目录的已清理且唯一的文件名。

原型

wp_unique_filename( string $dir, string $filename, callable $unique_filename_callback = null )

描述

如果文件名不是唯一的,那么在扩展名之前会将一个数字添加到文件名中,并且将继续添加数字,直到文件名是唯一的。

参数

$dir (string) (Required) 目录。

$filename (string) (Required) 文件名。

$unique_filename_callback (callable) (Optional) 打回来。

返回值

(string)  如果给出新文件名不是唯一的。

源文件

路径:wp-includes/functions.php

<?php
...
function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
	// Sanitize the file name before we begin processing.
	$filename = sanitize_file_name($filename);
	// Separate the filename into a name and extension.
	$ext = pathinfo( $filename, PATHINFO_EXTENSION );
	$name = pathinfo( $filename, PATHINFO_BASENAME );
	if ( $ext ) {
		$ext = '.' . $ext;
	}
	// Edge case: if file is named '.ext', treat as an empty name.
	if ( $name === $ext ) {
		$name = '';
	}
	/*
	 * Increment the file number until we have a unique file to save in $dir.
	 * Use callback if supplied.
	 */
	if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
		$filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
	} else {
		$number = '';
		// Change '.ext' to lower case.
		if ( $ext && strtolower($ext) != $ext ) {
			$ext2 = strtolower($ext);
			$filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
			// Check for both lower and upper case extension or image sub-sizes may be overwritten.
			while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
				$new_number = (int) $number + 1;
				$filename = str_replace( array( "-$number$ext", "$number$ext" ), "-$new_number$ext", $filename );
				$filename2 = str_replace( array( "-$number$ext2", "$number$ext2" ), "-$new_number$ext2", $filename2 );
				$number = $new_number;
			}
			/**
			 * Filters the result when generating a unique file name.
			 *
			 * @since 4.5.0
			 *
			 * @param string        $filename                 Unique file name.
			 * @param string        $ext                      File extension, eg. ".png".
			 * @param string        $dir                      Directory path.
			 * @param callable|null $unique_filename_callback Callback function that generates the unique file name.
			 */
			return apply_filters( 'wp_unique_filename', $filename2, $ext, $dir, $unique_filename_callback );
		}
		while ( file_exists( $dir . "/$filename" ) ) {
			$new_number = (int) $number + 1;
			if ( '' == "$number$ext" ) {
				$filename = "$filename-" . $new_number;
			} else {
				$filename = str_replace( array( "-$number$ext", "$number$ext" ), "-" . $new_number . $ext, $filename );
			}
			$number = $new_number;
		}
	}
	/** This filter is documented in wp-includes/functions.php */
	return apply_filters( 'wp_unique_filename', $filename, $ext, $dir, $unique_filename_callback );
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/wp_unique_filename/