# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Media](https://wpide.com/library/category/media/)
- Tags: uploads, file-names, seo
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/name-uploads-after-post/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Name Uploaded Files After Their Post" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
