Redirect attachment pages to parent post
- WordPress
For every image or file you upload, WordPress creates a dedicated attachment page at its own URL. These pages display the media file with minimal context and are considered thin content by search engines. Google has specifically flagged attachment pages as low-quality in their documentation.
<?php
/**
* Redirect Attachment Pages to Parent Post
*
* WordPress creates a dedicated URL for every uploaded media file. These
* pages have thin content (just the image/file) and dilute your SEO.
* Google has flagged them as low-quality pages. This redirects all
* attachment page requests to the parent post, or to the homepage if
* the attachment has no parent.
*
* Usage: Add to functions.php.
*
* @category wordpress
* @language php
*
* @author Adame Dahmani https://adame.io
* @support Support my family project: https://adame.io/fundraiser
*/
add_action( 'template_redirect', function () {
if ( ! is_attachment() ) {
return;
}
global $post;
if ( $post && $post->post_parent ) {
wp_redirect( get_permalink( $post->post_parent ), 301 );
} else {
wp_redirect( home_url( '/' ), 301 );
}
exit;
} );This redirects all attachment page requests to the parent post (where the media was uploaded), or to the homepage if there’s no parent. The 301 status tells search engines the redirect is permanent.