Last updated on September 13, 2023

Disable Attachment Pages

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Redirect attachment pages to the URL of attachment itself.

By default, WordPress creates attachment pages for media files (images, videos, audio, etc.) uploaded to your website. These pages can be accessed by clicking on the attachment link in the media library, which can result in duplicate content and other SEO issues. If you want to disable attachment pages in WordPress, you can use the following code snippet:

add_action( 'template_redirect', 'wpsnippets_disable_attachment_pages', 1 );

function wpsnippets_disable_attachment_pages () {

    global $wp_query;

    if ( is_attachment() ) {
        wp_safe_redirect( home_url() );
        exit();
    }
}

This code checks if the current page is an attachment page using the is_attachment() function. If it is an attachment page, it redirects the user to the home page of your website using the wp_safe_redirect() function. Once you have added this code to your functions.php file, attachment pages will be disabled and users will be redirected to the home page instead.

Last updated on September 13, 2023. Originally posted on April 30, 2023.

Leave a Reply

Your email address will not be published. Required fields are marked *