# Redirect Attachment Pages

> Sends visitors of media attachment pages to the post the file is attached to, or to the homepage for unattached files.

- Type: PHP
- Runs: Run everywhere
- Category: [Media](https://wpide.com/library/category/media/)
- Tags: media, attachments, redirect, seo
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/redirect-attachment-pages/

## Code

```php
add_action( 'template_redirect', function () {
    if ( ! is_attachment() ) {
        return;
    }

    $attachment = get_queried_object();
    $parent_id  = $attachment instanceof WP_Post ? (int) $attachment->post_parent : 0;
    $target     = ( $parent_id && 'publish' === get_post_status( $parent_id ) ) ? get_permalink( $parent_id ) : home_url( '/' );

    wp_safe_redirect( $target, 301 );
    exit;
} );
```

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Redirect Attachment Pages" 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/
