WordPress attached images gallery

In this tutorial, we want to show a gallery of all our images uploaded in WordPress, attached to posts. We will use the plugin MixItUp to sort the images.

Requirements

Result

Setup

We have a few posts in 2 categories: Hong Kong & Palo Alto. In each of the posts, we have uploaded pictures. We want to show a gallery of all the pictures we uploaded and sort them by their posts' categories.

Make sure the images are well attached to posts: go to Media Library and in the column "Uploaded to", there should be a post title.

Let's create the filters for our gallery.

<ul id="filters">
  <li class="filter" data-filter="all">All</li>
  <?php
    $args = array('exclude' => '1');
    // List all categories, we want to exclude our first category
    // Change the arguments as you like
    $categories = get_categories($args);
    foreach ($categories as $category) {
      echo '<li class="filter" data-filter="'. $category->slug .'">'. $category->name .'</li>';
    }
  ?>
</ul>

We will use the category slug to filter our images.

Let's style this with a bit of CSS:

#filters {
  text-align: center;
  padding: 10px 0;
  margin-bottom: 10px;
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
}
#filters li {
  display: inline-block;
  cursor: pointer;
  margin: 0 20px;
}
#filters li:hover {
  color: #ccc;
}

Now let's create our loop and show our attached images

<?php while ( have_posts() ) : the_post(); // start the loop ?>
  <ul id="gallery">
    <?php
      $args = array('post_type' => 'attachment', 'numberposts' => -1);
      // Get all attachments
      // Change the arguments as you like
      $attachments = get_posts($args);
      if ($attachments) {
        foreach ($attachments as $attachment) {
          $post_id = $attachment->post_parent;
          $post_cat = get_the_category($post_id);
          $post_title = get_the_title($post_id);
          $cat_name = $post_cat[0]->cat_name;
          $cat_slug = $post_cat[0]->slug;

          echo '<li class="mix '.$cat_slug.'">';
          // We are using the category slug to order the images
          echo '<a href="'. wp_get_attachment_url($attachment->ID) .'">';
          // Let's link everything to the full size image URL
          echo wp_get_attachment_image($attachment->ID, 'thumbnail');
          // Display the thumbnail
          echo '<p>';
          echo 'Cat: '. $cat_name .'<br />';
          echo 'Post title: '. $post_title .'<br />';
          echo 'Image: '. apply_filters('the_title', $attachment->post_title);
          echo '</p></a></li>';
          // Display the post category name, the post title, and the image title
        }
      }
    ?>
    <li class="break"></li>
  </ul>
<?php endwhile; // end of the loop. ?>

The CSS! We're using a grid layout technique with lists and inline-block, you can read about it more at Barrel blog.

#gallery {
  text-align: justify;
  font-size: 0;
}
#gallery:after {
  content: '';
  display: inline-block;
  width: 100%;
}
#gallery .break {
  width: 100%;
  height: 0;
  padding: 0;
  margin: 0;
}
#gallery li {
  // CSS below is for the grid technique
  display: inline-block;
  width: 18%;
  font-size: 11px;
  margin: 1%;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  // CSS below is for style
  background: #ddd;
  text-align: center;
  padding: 10px;
}
#gallery p {
  margin-top: 10px;
}
#gallery a {
  text-decoration: none;
}
// CSS below is for mixitup plugin
#gallery .mix {
  opacity: 0;
  display: none;
}

Important! In your JavaScript file, you need to instantiate MixItUp.

if($('#gallery').length) {
  $('#gallery').mixitup();
}

Final page template:

<?php
/**
 * Template Name: Attached images gallery
 *
 */
get_header(); ?>
  <div id="primary" class="site-content">
    <div id="content" role="main">
      <ul id="filters">
        <li class="filter" data-filter="all">All</li>
        <?php
          $args = array('exclude' => '1');
          // List all categories, we want to exclude our first category
          // Change the arguments as you like
          $categories = get_categories($args);
          foreach ($categories as $category) {
            echo '<li class="filter" data-filter="'. $category->slug .'">'. $category->name .'</li>';
          }
        ?>
      </ul>
      <?php while ( have_posts() ) : the_post(); // start the loop ?>
        <ul id="gallery">
          <?php
            $args = array('post_type' => 'attachment', 'numberposts' => -1);
            // Get all attachments
            // Change the arguments as you like
            $attachments = get_posts($args);
            if ($attachments) {
              foreach ($attachments as $attachment) {
                $post_id = $attachment->post_parent;
                $post_cat = get_the_category($post_id);
                $post_title = get_the_title($post_id);
                $cat_name = $post_cat[0]->cat_name;
                $cat_slug = $post_cat[0]->slug;

                echo '<li class="mix '.$cat_slug.'">';
                // We are using the category slug to order the images
                echo '<a href="'. wp_get_attachment_url($attachment->ID) .'">';
                // Let's link everything to the full size image URL
                echo wp_get_attachment_image($attachment->ID, 'thumbnail');
                // Display the thumbnail
                echo '<p>';
                echo 'Cat: '. $cat_name .'<br />';
                echo 'Post title: '. $post_title .'<br />';
                echo 'Image: '. apply_filters('the_title', $attachment->post_title);
                echo '</p></a></li>';
                // Display the post category name, the post title, and the image title
              }
            }
          ?>
          <li class="break"></li>
        </ul>
      <?php endwhile; // end of the loop. ?>

    </div><!-- #content -->
  </div><!-- #primary -->

<?php get_footer(); ?>

Now, create a new page using the template "Attached images gallery"!

4 comments

  1. Alain 30 September 2013 at 07:26:08

    Bonjour et merci pour votre article.

    J'ai réalisé la maquette qui fonctionne très bien mais je me heurte à un problème qui est certainement simple mais difficile pour moi car je ne suis pas développeur.

    Je souhaite filtrer les catégories à partir des catégories des images et non pas celles des articles. En effet, mon blog permet de taguer les images. Le filtre fonctionne mais la commande ne fonctionne pas. Il y a modification à faire mais je tâtonne et je perds mon temps, peut-être pouvez-vous m'aider ?

    Encore merci et A+

    • Karine 30 September 2013 at 17:43:36

      Bonjour,
      Tout d'abord, à la création des filtres, il ne faudra pas utiliser get_categories() mais plutôt quelque chose comme get_terms() avec en premier argument la taxonomie des "tags" de vos images. Par ex get_terms('image_tag').

      Dans la boucle/loop, au lieu de:
      $post_id = $attachment->post_parent;
      $post_cat = get_the_category($post_id);
      $post_title = get_the_title($post_id);
      $cat_name = $post_cat[0]->cat_name;
      $cat_slug = $post_cat[0]->slug;
      etc.
      Il faudra adapter en utilisant get_the_term() plutôt que get_the_category().
      La ligne $post_id = $attachment->post_parent; vous est inutile puisque vous ne vous souciez pas de l'article et il faudra que $post_id ait la valeur de l'ID de l'image...

      J'espère que ça vous aide...! N'hésitez pas à me contacter si ça ne marche pas ! Merci !

  2. Tom 24 January 2014 at 10:37:31

    I greatly appreciate the tutorial. My skills are sorely lacking. I have created a semi-functioning version with one exception, the selections unselect immediately after showing what I'd like. It's almost like it refreshes the page after the selection is made.

    If time and interest allows I would greatly appreciate any help you might be able to provide.

    The example site is at http://augmenting.me/inspiration/sort/.

    Thanks again.

    • Tom 28 January 2014 at 09:02:49

      Please disregard the question. I went another route. Thanks again.

Comments are closed.