Filters wp_unique_filename during sideloads.
Description
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-150×150.jpeg, and when uploading myphoto-150×150.jpeg, it will be renamed to myphoto-150×150-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 WP_REST_Attachments_Controller::sideload_item() pins the upload to the attachment’s own directory, so any name returned here belongs to the attachment being extended.
Parameters
$filenamestringrequired- Unique file name.
$dirstringrequired- Directory path.
$numberint|stringrequired- The highest number that was used to make the file name unique or an empty string if unused.
$attachment_filenamestring|nullrequired- Original attachment file name.
Source
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;
}
Changelog
| Version | Description |
|---|---|
| 7.1.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.