How to Disable Attachment Pages in WordPress

WordPress creates an attachment page for each file uploaded to the Media Library.

Background

Each time we upload a file to the Media Library, WordPress stores the file in the uploads folder and creates a new attachment. Attachments are instances of the 'attachment' built-in post type.

Attachment pages are useful to display information about the underlying file, as I do here, but website owners may prefer to bypass these intermediate pages and link directly to the file.

Theory

The fact that a new attachment is created each time we upload a file to the Media Library cannot be disabled, but we can make these pages unreachable.

In the next section, I propose a solution that uses the 'template_redirect' action to redirect attachment pages to the underlying file. I also use the 'attachment_link' filter to replace the attachment page URL with the file URL to avoid unnecessary redirects.

Learn here how to use actions and filters in WordPress.

Steps

Follow these steps to bypass attachment pages in WordPress.

Step 1: Add the following code to WordPress.

/*
 * Performs a redirect from an attachment page to the underlying file.
 */
function ns_redirect_attachment(){

    if(is_attachment()){
        $attachment_ID = get_queried_object_id();
        $file_url = wp_get_attachment_url($attachment_ID);
        wp_redirect($file_url, 301);
        exit();
    }
}
add_action('template_redirect', 'ns_redirect_attachment', 10, 0);

/*
 * Replaces the attachment page URL with the URL of the underlying file.
 */
function ns_replace_attachment_link($link, $post_ID){
    return wp_get_attachment_url($post_ID) ?: $link;
}
add_filter('attachment_link', 'ns_replace_attachment_link', 10, 2);

Step 2: Try to visit an attachment page and verify that the underlying file is opened.

Further reading

I recommend the other tutorials in this series to learn more about managing attachments in WordPress.

Exercise

Develop a solution that redirects each attachment to the post it is attached to. If the attachment is not attached to a post, redirect to the underlying file. Customize the attachment link accordingly.

Source code

The source code developed in this tutorial, including a possible answer to the exercise, is available here.