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
- Open your active theme’s
functions.phpfile or a custom functionality plugin. - Add the code below.
- Save the file.
- 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' );