Redirect Attachment Pages to Their Parent Post
Permanently redirects WordPress attachment pages to their parent post, preventing thin content pages from accumulating in search indexes.
PHPby SnipCraft
php
<?php
if ( ! function_exists( 'scseed_redirect_attachment_pages' ) ) {
function scseed_redirect_attachment_pages() {
if ( ! is_attachment() ) {
return;
}
global $post;
if ( $post && $post->post_parent ) {
$parent_url = get_permalink( $post->post_parent );
if ( $parent_url ) {
wp_redirect( esc_url( $parent_url ), 301 );
exit;
}
}
// No parent — redirect to the homepage.
wp_redirect( esc_url( home_url( '/' ) ), 301 );
exit;
}
add_action( 'template_redirect', 'scseed_redirect_attachment_pages' );
}#301#attachments#redirect#seo#thin-content