WordPress Shortcode: easily display the last image attached to post

January 20, 2009 at 8:34 am

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!