1function myprefix_redirect_attachment_page() {
2 if ( is_attachment() ) {
3 global $post;
4 if ( $post && $post->post_parent ) {
5 wp_redirect( esc_url( get_permalink( $post->post_parent ) ), 301 );
6 exit;
7 } else {
8 wp_redirect( esc_url( home_url( '/' ) ), 301 );
9 exit;
10 }
11 }
12}
13add_action( 'template_redirect', 'myprefix_redirect_attachment_page' );