Image/Attachment Templates for WordPress

Ever since about WordPress v2.6 or so, images you uploaded and inserted into a WordPress post were created as attachments, a sub-post type that belongs to the post or page they are attached to. These attachment posts can be given their own template, and indeed they look for one when you visit the attachment’s permalink. The K2 theme ships with image and attachment templates (named image.php and attachment.php in the theme template hierachy) and displays the file along with some meta data and, if the image is a part of a gallery (or there is more than one attachment on the post), navigation aids to move from one attachment to the next. For many sites this is ideal, but if you want to just give people the file, and avoid having to create these attachment templates, then here’s a neat trick I cooked up on a recent project.

Put this bit of code in your functions.php (or in a plugin file and activate it):


add_action('my_attachment_redirect', 'my_attachment_redirect');
function my_attachment_redirect()
{
global $posts;
header('Location: '.$posts[0]->guid);
}

Then just call the action we created as the only code in your image.php and attachment.php templates:


<?php do_action('my_attachment_redirect'); ?>

Now when users visit the permalink for the attachment, they will be redirected to the actual file path. The rest is handled by the browser. For instance, images should be displayed in the browser window and PDFs downloaded or displayed inline (depending on what normally happens for that user when they encounter a PDF link).

4 Responses to “Image/Attachment Templates for WordPress”


  • I’ve always uploaded my images to Flickr & used the image source feature when putting in pictures in Wordpress.

  • Hi Eric,
    I’m trying to set up your Intagram Oembed Plugin for Wordpress, and I’m finding that the sizes don’t work for my blog layout. I need a size right between the M and L, is there any way for me to adjust this setting? Also, I’m still trying to figure out exactly how this works… I would love for this to be an automatic update to my WP blog whenever I publish with instagram on my phone (just like it does to my facebook and twitter accounts), does this plugin have that capability? Or will I be embedding each image manually in a new post?

    I love this plugin by the way, and I too am a fan or scotch. Well, maybe not scotch per say… but rather hard alcohol in general.

Leave a Reply