WordPress: get and display images from the Media Library

WordPress: get and display images from the Media Library

How to get and display images taken from the WordPress Media Library.

Although it may seem odd, WordPress handles all the images contained in the Media Library as posts. More specifically, images are considered as attachments, that is, their post_type value is set to attachment. This is not enough, though, to get an image from the Media Library. In fact, also PDF files are considered as attachments so that we have to specify the post_mime_type parameter as well (in this case is image). To understand the procedure behind the getting and displaying images taken from the Media Library, in this article we'll build a simple image gallery featuring random images.

All our code must be placed in the functions.php file. First of all, we get the images we want:

function get_images_from_media_library() {
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' =>'image',
        'post_status' => 'inherit',
        'posts_per_page' => 5,
        'orderby' => 'rand'
    );
    $query_images = new WP_Query( $args );
    $images = array();
    foreach ( $query_images->posts as $image) {
        $images[]= $image->guid;
    }
    return $images;
}

We use the WP_Query class by passing to its constructor an array of parameters. This array specifies the post type, the MIME type, the post status, the number of items to retrieve and the order by which they will be returned.

Then we populate another array by extracting the full URL of each image (guid). By doing so, we make sure that we'll use the full-sized images in our gallery.

Our next step is to create the HTML gallery:

function display_images_from_media_library() {

	$imgs = get_images_from_media_library();
	$html = '<div id="media-gallery">';
	
	foreach($imgs as $img) {
	
		$html .= '<img src="' . $img . '" alt="" />';
	
	}
	
	$html .= '</div>';
	
	return $html;

}

We've simply built an HTML string by looping through the array which contains all our image URLs. Finally, we can use our function in our theme as follows:

<?php echo display_images_from_media_library(); ?>

Of course the CSS styling is entirely up to your preferred design choice.