DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

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) {
		"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:


Many thanks to Madcore for this awesome recipe!

One Comment

  1. This worked perfectly! Thanks!

    I am trying to set up a few functions to be able to use shortcode to insert the attached images from each post automatically by either the order they were uploaded by filename or something that I can control.

    This takes care of part of my problem. Can this be adapted to insert the first image, or the second image?

Leave a Comment

Your email address will not be published. Required fields are marked *