Name Uploaded Files After Their Post
Renames files uploaded from inside the post editor to match the post's slug, so "DSC_0042.jpg" becomes "summer-menu.jpg", which is better for image search.
Opens WPIDE on
Code
add_filter( 'wp_handle_upload_prefilter', function ( $file ) {
$post_id = isset( $_REQUEST['post_id'] ) ? absint( $_REQUEST['post_id'] ) : 0;
if ( ! $post_id || ! empty( $file['error'] ) || ! current_user_can( 'edit_post', $post_id ) ) {
return $file;
}
$post = get_post( $post_id );
$slug = $post ? ( $post->post_name ? $post->post_name : sanitize_title( $post->post_title ) ) : '';
if ( '' === $slug || 0 === strpos( $slug, 'auto-draft' ) ) {
return $file;
}
$extension = strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) );
$file['name'] = $slug . ( $extension ? '.' . $extension : '' );
return $file;
} );
Notes
Only files uploaded while editing a post or page are renamed. WordPress adds -1, -2 and so on when a name is taken.
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.