Skip to content

Instantly share code, notes, and snippets.

@lxbdr
Created February 27, 2020 12:03
Show Gist options
  • Save lxbdr/7cbd858b0d090753ae4495c9c9bb255e to your computer and use it in GitHub Desktop.
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.
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