Post Pic

WordPress Shortcode: easily display the last image attached to post

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

Jan 20 2009 14:09

Awesome tip! Beats a whole lot of plugins out there!

Jan 20 2009 16:55

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/

Jan 30 2009 00:04

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 ?

Jan 30 2009 00:27

@SurfAnna: A shortcode can only be pasted on your editor (in html mode). So, this code can’t be used in your header.

Jan 30 2009 10:38

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.

Jan 30 2009 12:01

@SurfAnna: Sure it is possible, but the code needs some tweaking to work as you expect. Good luck!

Jan 30 2009 16:45

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…

Feb 03 2009 10:12

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.

Apr 17 2009 19:13

nice, really nice!

May 10 2009 22:26

How can I get attached flash video files?

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required