WP_REST_Attachments_Controller::filter_wp_unique_filename
Filters wp_unique_filename during sideloads.
wp_unique_filename() will always add numeric suffix if the name looks like a sub-size to avoid conflicts. Adding this closure to the filter helps work around this safeguard.
Example: when uploading myphoto.jpeg, WordPress normally creates myphoto-150x150.jpeg, and when uploading myphoto-150x150.jpeg, it will be renamed to myphoto-150x150-1.jpeg However, here it is desired not to add the suffix in order to maintain the same naming convention as if the file was uploaded regularly.
The suffix is only dropped when no file of that name already exists in $dir, so this never returns a name that would overwrite one. The unsuffixed name must also derive from the attachment's own file name, and {@see self::sideload_item()} pins the upload to the attachment's own directory, so any name returned here belongs to the attachment being extended.
Method of the class: WP_REST_Attachments_Controller{}
No Hooks.
Returns
string. Filtered file name.
Usage
$result = WP_REST_Attachments_Controller::filter_wp_unique_filename( $filename, $dir, $number, $attachment_filename );
- $filename(string) (required)
- Unique file name.
- $dir(string) (required)
- Directory path.
- $number(int|string) (required)
- The highest number that was used to make the file name unique or an empty string if unused.
- $attachment_filename(string|null) (required)
- Original attachment file name.
Changelog
| Since 7.1.0 | Introduced. |
WP_REST_Attachments_Controller::filter_wp_unique_filename() WP REST Attachments Controller::filter wp unique filename code WP 7.1
private static function filter_wp_unique_filename( $filename, $dir, $number, $attachment_filename ) {
if ( ! is_int( $number ) || ! $attachment_filename ) {
return $filename;
}
$ext = pathinfo( $filename, PATHINFO_EXTENSION );
$name = pathinfo( $filename, PATHINFO_FILENAME );
$orig_name = pathinfo( $attachment_filename, PATHINFO_FILENAME );
if ( ! $ext || ! $name ) {
return $filename;
}
$matches = array();
if ( preg_match( '/(.*)-(\d+x\d+|scaled)-' . $number . '$/', $name, $matches ) ) {
$filename_without_suffix = $matches[1] . '-' . $matches[2] . ".$ext";
if ( $matches[1] === $orig_name && ! file_exists( "$dir/$filename_without_suffix" ) ) {
return $filename_without_suffix;
}
}
return $filename;
}