[WordPress | Tip] Redirect Image Attachment Pages

  • Thread starter Thread starter Deleted member 877043
  • Start date Start date
D

Deleted member 877043

Guest
WordPress is great, but some things could be optimized. One of these is the so-called "attachment pages."

Attachment pages show the image or audio file that you've uploaded and added in a page or post. You can even go as far as to add textual content to these attachment pages and get your SEO game going, but most of the time these pages are a pain in the rear. Not only because these attachment pages could ef up your SEO game, but also because a visitor that happens to land on one of these pages can potentially leave a "comment," and we don't want that to happen.

Disabling the attachment pages is possible with the help of Yoast SEO, but not all of us are fans of Yoast and prefer to use another SEO plugin. So, the question remains; how do you prevent people from landing on an attachment page? The answer to that is simple; use some custom coding to redirect all of the "attachments" to the page or post they're used on. In this case, it involves creating a page template for the attachment page we don't need; images.

The code below contains a simple redirect command that tells WordPress to redirect the current attachment page back to its parent page (all media attachments in a WP page or post have a child-parent relationship with the page or post that you create.)

In this example, I'm trying to prevent all the image uploads from having their separate attachment pages by simply creating a file called "image.php" and adding the contents below. After that is done, I upload "image.php" to the root directory of my theme or child-theme (!! READ CAREFULLY: THEME OR CHILD THEME!!), and I'm done. No more pesky attachment pages and no more unwanted comments.

Code:
<?php
/**
 * The template for displaying all image attachments.
 * We use this template to prevent WordPress from showing the media attachment pages
 * and not have some random stranger leave a comment on the attachment page.
 *
 * @link https://developer.wordpress.org/themes/template-files-section/attachment-template-files/
 * @link https://developer.wordpress.org/reference/functions/get_permalink/
 *
 * @package WordPress
 * @subpackage YOUR THEME NAME
 * @since 1.0
 * @version CURRENT VERSION
 **/

wp_redirect( get_permalink( $post->post_parent ) );

You could also use this for other MIME types, like video. I.e., substitute the word "image.php" with "video.php."

Hope this is helpfull to some of my fellow BHWers.
 
Back
Top