Skip to main content
Login Join
Snippet · PHP

Disable Attachment Pages and Redirect to the Media File

Shared by Amit Dholiya · July 24, 2026

Back to Snippets

Description

WordPress creates a separate attachment page for every uploaded media file. These pages often provide little value and can lead to thin content. This snippet redirects visitors from attachment pages directly to the original media file.

Steps

  1. Open your active theme’s functions.php file or a custom functionality plugin.
  2. Add the code below.
  3. Save the file.
  4. Visit any attachment page to verify it redirects to the media file.
/**
 * Redirect attachment pages to the media file.
 */
function wpfolks_redirect_attachment_pages() {

    if ( is_attachment() ) {
        global $post;

        if ( $post ) {
            wp_redirect( wp_get_attachment_url( $post->ID ), 301 );
            exit;
        }
    }
}
add_action( 'template_redirect', 'wpfolks_redirect_attachment_pages' );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments