Post Wordpress Attachments Media Redirects

Redirect WordPress attachment urls to the file url

Been having clients upload PDF docs to WordPress in the usual way, WordPress then creates a post url for that file upload - no worries.

Trouble is many clients are then using this as the link to the document and then wondering why when they click the link they are just taken to another page on the site with a link to the file which is basically the link they just clicked on.

This is also an issue when using advanced custom fields page picker for links as the page picker selects the media post url generated by WordPress not the actual file url. Anyway...

You can solve this by creating a media template file - http://codex.wordpress.org/Template_Hierarchy#Attachment_display - using this you can also only target certain media types for redirect. For my specific needs I needed to redirect attachments like PDFs from their attachment url e.g. http://yoursite.com/?attachment_id=607 to the actual file url e.g. http://yoursite.com/wp-content/uploads/a-nice-document.pdf

So:

1 - Create an attachment.php file in your WordPress theme folder

2 - Put this code in the file:

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

3 - Upload it and there you go

Anyone requesting http://yoursite.com/?attachment_id=607 will be 301 redirected (permanent redirect) to http://yoursite.com/wp-content/uploads/a-nice-document.pdf

If you only want a temporary redirect or any other type of redirect just replace 301 in the code with the desired redirect i.e.

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

302 is the default if you don't specify this in wp_redirect.