Will McLean
Process diary

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

Last modified: December 11, 2017
Created: November 25, 2017

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
else:
    _e( 'Sorry, no posts matched your criteria.' );
endif;

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()) {
    session_start();
}

This is a Knowledge Base post.