Redirect Attachment Pages
Sends visitors of media attachment pages to the post the file is attached to, or to the homepage for unattached files.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
if ( ! is_attachment() ) {
return;
}
$attachment = get_queried_object();
$parent_id = $attachment instanceof WP_Post ? (int) $attachment->post_parent : 0;
$target = ( $parent_id && 'publish' === get_post_status( $parent_id ) ) ? get_permalink( $parent_id ) : home_url( '/' );
wp_safe_redirect( $target, 301 );
exit;
} );
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.