Will McLean is a designer and artist working in the Central Coast of NSW where he lives with his wife and 2 children.

Will is a meticulous developer and favours simplicity and clarity within his code. He can’t stand writing things twice so searches for any way to automate. His experiments can be found in the Exercises section of this site.

Will designs within systems. No project is too small for a design system. He favours the unusual, if not, how can he progress? You can read about his work in the Case Studies section of this site.

Updated: December 11, 2017

This is a Knowledge Base post.

Create an archive page of all the media on your WordPress site.

When developing this site I needed to write a WordPress loop that showed all of the media that was in the media library. As I had partitioned all of my work into posts I wanted somewhere I could view the images only and then click through to the post with which the image was associated with if the image piqued my interest. You can see this in effect in the media archive section of my site.

This is relatively easy once digging around the WordPress codex. First, write the loop to show all the images using attachment as the post type. I ordered it randomly (see note below). Make sure you enable pagination using the paged option. I also seem to have set the post status as inherit. I can’t seem to find what that does so I have made a note to revisit it at some point. If anyone has any ideas please get in contact.

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
    'post_type' => array( 'attachment' ),
    'post_status' => array( 'inherit' ),
    'paged' => $paged,
    'orderby' => 'RAND(1)',
$the_query = new WP_Query( $args ); 
if ( $the_query->have_posts() ) :
    // The image and link
    _e( 'Sorry, no posts matched your criteria.' );

Now add the code to show the image and the link to the post that the image was posted in. We can use the post ID to get the actual image and then we need to find the post_parent id to add a link to that post and its title.

echo wp_get_attachment_image( $post->ID, 'small' );
$parent = get_post_field( 'post_parent', $id);
$link = get_permalink($parent);
$title = get_the_title($parent);
echo '<p class="wp-caption-text">Posted in <a href="' . $link . '">' . $title . '</a></p>';

It must be noted that you have to make sure you don’t upload media that you don’t want to appear in this archive. It shows ALL the media in your archive. It would be pretty easy to add a test to see if it had a post parent before showing it but I haven’t done that yet.

NOTE: If you order your posts randomly and want pagination like I did you need to enable a php session to store your random query. Otherwise, every time you click on the pagination it gives you another random order. This renders the pagination useless. You can do this by adding the below to your functions.php file

if (!session_id()) {