Redirect WordPress attachment urls to the file url

Published: August 14, 2014 | Last Modified: October 3, 2017

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 - - 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. to the actual file url e.g.


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 will be 301 redirected (permanent redirect) to

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.