How to make a page template to list all galleries?

I’m trying to code a theme where I’ll have a universal gallery page. Basically like:

http://www.engadget.com/galleries/

However I’m at a loss for what I’d use to call all the galleries. I need the galleries to be custom post types (so I have domain.com/gallery/title-of-gallery/), but the galleries also have to be able to be inserted into posts via (or something like that). Also, the galleries have to have some sort of category assigned to them (like Reviews or Previews).

I also need to be able to insert multiple galleries into one post for reviews (where multiple galleries may be needed).

Does anyone have any way I’d be able to achieve this?

1 Answer
1

The underlying question here is How do I query all posts with image galleries? (since, once you have such a query, creating a custom template page to loop through them is fairly trivial).

One method would be:

  1. Custom query of attachment posts with a mime_type of image
  2. Loop through them, and add $post->post_parent to an array
  3. Custom query of posts, passing the above array of post IDs as post__in
  4. Loop through them, and output whatever you would like for each

Perhaps like so:

<?php
// Custom query args for image attachments
$image_attachments_query_args = array(
    'post_type' => 'attachment',
    'mime_type' => 'image'
);
// Query image attachments
$image_attachments = new WP_Query( $image_attachments_query_args );

// Loop through them and get parent post IDs
$gallery_post_ids = array();

foreach ( $image_attachments as $image_attachment ) {
    $gallery_post_ids[] = $image_attachment->post_parent;
}

// Custom query args for gallery posts
$gallery_posts_query_args = array(
    'post__in' => $gallery_post_ids
);

// Query gallery posts
$gallery_posts = new WP_Query( $gallery_posts_query_args );

// Loop through gallery posts

if ( $gallery_posts->have_posts() ) : while ( $gallery_posts->have_posts() ) : $gallery_posts->the_post();
    // Loop output goes here
endwhile; endif;
wp_reset_postdata();
?>

Note that this pulls all posts with even a single image attachment. You could maybe get fancy when looping through image attachments, and do something like:

// Placeholder array for IDs
$temp_post_ids();

// Final array for gallery post IDs
$gallery_post_ids = array();

// Loop through them and get parent post IDs
foreach ( $image_attachments as $image_attachment ) {
    // Add ID to the placeholder array
    $temp_post_ids[] = $image_attachment->post_parent;
    // If this post ID has multiple image attachments,
    // add it to the gallery posts query;
    // This will prevent posts with only a single
    // attached image from being queried in the next step
    if ( in_array( $image_attachment->post_parent, $temp_post_ids ) ) {
        $gallery_post_ids[] = $image_attachment->post_parent;
    }
}

Leave a Comment