Add a Random Suffix to Uploaded File Names
Appends a short random string to the name of every uploaded file (for example report-k3f9q2.pdf), so private documents cannot be found by guessing their URL.
Opens WPIDE on
Code
// Extensions to rename; leave empty to rename every upload.
$wpide_random_types = array( 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'csv', 'zip', 'txt' );
add_filter( 'wp_handle_upload_prefilter', function ( $file ) use ( $wpide_random_types ) {
if ( ! empty( $file['error'] ) || empty( $file['name'] ) ) {
return $file;
}
$info = pathinfo( $file['name'] );
$ext = isset( $info['extension'] ) ? strtolower( $info['extension'] ) : '';
if ( $wpide_random_types && ! in_array( $ext, $wpide_random_types, true ) ) {
return $file;
}
$file['name'] = $info['filename'] . '-' . strtolower( wp_generate_password( 6, false ) ) . ( $ext ? '.' . $ext : '' );
return $file;
} );
Notes
Set $wpide_random_types to limit it to documents if you want image file names to stay clean for SEO.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.