Attachment page redirect ( 301 Moved Permanently )

Last update: 11 January 2024
The function will redirect (301 Moved Permanently) from the attachment page to the parent post or to the main page of the site.
Attachment page redirect ( 301 Moved Permanently )

Saves the search engine crawler budget and removes unnecessary pages from the search index.

Add code in your file function.php

Tested:
WordPress 6.4.2
PHP 7.4

/**
 * Attachment page redirect. 301 Moved Permanently 
 *
 * @since 1.0.0
 */
function wphaf_is_attachment_redirect() {

  global $post;

  if ( is_attachment() ) {

    if ( $post && $post->post_parent ) {
      wp_redirect( esc_url( get_permalink( $post->post_parent ) ), 301 );
      exit;
    } else {
      wp_redirect( esc_url( home_url() ), 301 );
      exit;
    }
  }

}

add_action( 'template_redirect', 'wphaf_is_attachment_redirect' );