Gordonmac Dot Com

Mostly a web development blog

Adding attached images to a WordPress page

Posted: March 2nd, 2011 | Tags: | Posted in: PHP, Tutorials, Wordpress
Note: This tutorial was originally published in 2011. The tips and techniques explained may be outdated.

If you want to display images attached to a WordPress page/post all you need to do is copy the code below to your theme’s functions.php file:

/* Sizes can be thumbnail, full, medium, large */
function getAttachedimages($size='full', $before = '', $after = '')
{ 
	global $post;
	$qty = -1;
	if ( $images = get_children(array(
		'post_parent' => $post->ID,
		'post_type' => 'attachment',
		'numberposts' => $qty,
		'post_mime_type' => 'image',
		'order' => 'DESC', 
		'orderby' => 'menu_order ID'
	)))
	{
		foreach( $images as $image ) 
		{
			$attachmenturl = wp_get_attachment_url($image->ID);
			$attachmentimage = wp_get_attachment_image( $image->ID, $size );
			echo $before . $attachmentimage . $after . "n";
		}
	}
}

Usage

Using the function is a simple case of calling the function something like this:

<ul id="gallery">
<?php getAttachedimages('thumbnail', '<li>', '</li>'); ?>
</ul>

Have fun!