Created
February 27, 2020 12:03
-
-
Save lxbdr/7cbd858b0d090753ae4495c9c9bb255e to your computer and use it in GitHub Desktop.
Prevent upload in WordPress media library if there is already a file with the same name.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_filter( 'wp_handle_upload_prefilter', function ( $file ) { | |
$uploads = wp_upload_dir(); | |
$use_yearmonth = get_option( 'uploads_use_yearmonth_folders' ); | |
if ( boolval( $use_yearmonth ) ) { | |
// if upload to year month based folders is enabled check current target | |
$year = date( 'Y' ); | |
$month = date( 'm' ); | |
$target = $uploads['path'] . DIRECTORY_SEPARATOR . $year . DIRECTORY_SEPARATOR . $month . DIRECTORY_SEPARATOR . $file['name']; | |
} else { | |
// uploads dir | |
$target = $uploads['path'] . DIRECTORY_SEPARATOR . $file['name']; | |
} | |
if ( file_exists( $target ) ) { | |
$file['error'] = 'File with the same name already exists.'; | |
} | |
return $file; | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment