I was looking in GWMT recently and noticed 400 more URL’s than posts published have been indexed. I guess its because of image attachment pages which is why i’ve written this post.
To redirect attachment pages to the parent post URL, there are at least 5 different solutions to choose from:
- Write a custom function with conditional tag using both the wp_redirect function and template_redirect function.
- Add 1 line of redirect code directly to your themes attachment or image.php file.
- Use the settings in the WordPress SEO by Yoast plugin if installed.
- Install the Attachment Page Redirect plugin or similar.
- Genesis Users: Create a new attachment.php or image.php file which includes the redirect to post parent URL code and upload it to your child themes root directory.
1. Custom Function With Redirect
Simply copy this PHP code from the view raw link in the Gist and paste it at the end of your child themes functions.php file.
2. Add Redirect to image.php
- Create a new file using a code editor.
- Copy the code from the View raw link in the Gist labelled image.php
- Paste the code into the file and upload it to your child themes root directory.
Tested on the Twenty Fourteen default theme for WordPress.
3. WordPress SEO Permalink Settings
4. Attachment Page Redirect plugin
5. Genesis Attachment File With Redirect
- Create a new file named attachment.php using a code editor like Notepad++
- Copy the PHP from the view raw link in the Gist.
- Paste the code into the file and upload it to the root directory of your child theme
If you have found another way to redirect attachment pages to the parent post, please add the solution in the comments.
I’ll update this post if it makes any difference and let you know what happened.
Thanks for the nice code snippet Brad. Unfortunately, Yoast SEO now redirects Attachment URLs to direct media file instead to the attached page or post, so used the first method and it works great!
Kind regards,
Shyam
Most of my attachment pages are indexed in Google. Is all attachment pages will removed once i follow above method?
What do I do to remove the index Attachment URLs
illustrating images: https://i.imgur.com/16u6E3h.png
This is the link I used in the image above: https://agiare.vn/pin-sac-du-phong.html
Thanks!
Coding support is only provided to registered users https://wpsites.net/register/
I’ve been using something similar to method 1 but have recently found ‘unattached’ attachments aren’t redirected. Any suggestions on how to redirect ‘unattached’ attachment images to, let’s say, the homepage?
Does this method redirect attachment files too?
Depends on which method you use.
You can redirect all attachments, image attachments only or anything you like depending on which method you use.