How to Stop Google from Indexing your WordPress Image Attachment Pages ?

Just add the below code to your functions.php.
First of all this code checks if the attachment is related post or not if related then it redirect to the particular post else it is redirect to your home page.

function media_redirect_attachment_page() {
if ( is_attachment() ) {
  global $post;
  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', 'media_redirect_attachment_page' );
Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *