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()); ?>
Leave a Reply