Bypassing WordPress Attachment Posts

This problem has been bugging me for a while now and finally I have managed to find a fix that seems to work well.  The problem being that clients, when linking to something they have uploaded to a page or post never click the ‘File URL’ for the link, instead leaving it on ‘Post URL’ which causes problems.  Here is how I fixed it.

When clients forget to click the File URL button it means that when they click on a link, instead of being show the file that they think they are linking to they are shown the post that WordPress creates for that attachment.  If the attachment is an image this not a major issue as you can include a custom image.php file in your theme folder and make that page looks nice. However if the link is to a PDF for example the user is simply presented with another post with the same link in that they just clicked on.  Worse still is that if the author has not added a title tag to the attachment they will see an ugly link.

First I wanted to see if there was a way to make WordPress default to the File URL rather than always placing the Post URL in the attachments link option. I drew a blank on this search but then came across a handy WordPress function called wp_redirect().  What this does is redirects the user to an absolute URL.  Therefore I combined this with wp_get_attachment_url() and hey presto, everytime a link is clicked to a file that has been uploaded in WordPress, whether an image or not the user gets sent straight to the files location and not the attachment post.  The code I placed in my attachment.php page is below:

<?php wp_redirect(wp_get_attachment_url()); ?>

6 responses

  1. This is cool, but where I am supposed to stick this function. I’m getting annoyed to see my internal images appearing with weird URL that are being indexed from Google, and removing URLs from the GWT it’s not a solution.

    Can you please explain where the above lines need to be included?

    Thanks

    1. Add this code to your themes image.php file. If there is not one just create one with this code inside.

  2. You’re a lifesaver. I was creating a custom PDF search for a client but the search results were directing end users to the attachment pages rather than directly to the PDF. Here’s my only question…do you have any suggestions on how to make the redirect open in a new window?

    1. I would have thought adding target="_blank" attribute into your img tag would do the trick.

  3. I have a custom theme and I cannot see an attachment.php or image.php file to edit how do I go about working out where I can add this code?

    1. You should just be able to add an attachment.php file and then place the code in there. Add the file in your themes root folder or better still create a child theme and add it in there!

Leave a Reply

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