
Some time ago, I have shown you how to create and use WordPress shortcode. One of our readers, Madcore, created a very helpful shortcode to easily display the last image attached to post. Here’s the code.

Some time ago, I have shown you how to create and use WordPress shortcode. One of our readers, Madcore, created a very helpful shortcode to easily display the last image attached to post. Here’s the code.
First, you have to paste the following code in your functions.php file, in order to create the shortcode.
function sc_postimage($atts, $content = null) {
extract(shortcode_atts(array(
"size" => 'thumbnail',
"float" => 'none'
), $atts));
$images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . get_the_id() );
foreach( $images as $imageID => $imagePost )
$fullimage = wp_get_attachment_image($imageID, $size, false);
$imagedata = wp_get_attachment_image_src($imageID, $size, false);
$width = ($imagedata[1]+2);
$height = ($imagedata[2]+2);
return '<div class="postimage" style="width: '.$width.'px; height: '.$height.'px; float: '.$float.';">'.$fullimage.'</div>';
}
add_shortcode("postimage", "sc_postimage");
Once done, you can easily display the last image attached to post by using the postimage shortcode as shown below:
[postimage]
Many thanks to Madcore for this awesome recipe!
22 Responses
Awesome tip! Beats a whole lot of plugins out there!
You can use the GetImage plugin too.
Its easy to use on your templates. To use, you need to write only this line:
[?php gi_full(true);?]
And, if you wants the second image, you only need to pass the pos of the atachament image.
[?php gi_full(1, 5); ?]
http://wordpress.org/extend/plugins/get-image/
Hi, I’m not sure to understand how to use this code. Can I use it to display anywhere (e.g. the header) the picture of my last post ? And can I put the sortcode anywhere in my code ?
@SurfAnna: A shortcode can only be pasted on your editor (in html mode). So, this code can’t be used in your header.
Hm, that’s what I guessed…
But surely I can use the original code : I’d like to display my last pic(s) in my header (like a sort of diaporama). I’ll see what I can / be able to do!
Thanks for your help and good tips. I’ve found loads of useful hacks on your blogs.
@SurfAnna: Sure it is possible, but the code needs some tweaking to work as you expect. Good luck!
Thanks, I will need it !
Some time ago, I found a great WP theme which does that (the function I talked about), but I can’t find anymore. I should have bookmarked it…
With shortcode, and a similar code, you can display all the attached documents of a post.
I developped a plugin named EG-Attachments for that.
You can download it in the wordpress repository.
nice, really nice!
How can I get attached flash video files?
Trackbacks: