The WordPress Gallery, Grabbing The Link and Images?

I have created a template for gallery named image.php which allows me to create a news website style image gallery that can be embedded in posts. But I need two more things to make this complete.

  • First, I want to know how to create a text link to the first image in a gallery, rather than displaying thumbnails for the gallery as the built-in shortcode currently does.
    For example, check out “click here to start” on this page: http://www.businessinsider.com/android-vs-iphone-debate-quotes-2011-12

  • Secondly, if anybody knows how to generate a list of all the images in a gallery which I can add to my image.php file that would be great to have so I could use it to create a slider on the bottom of each page featuring an image with the other images in the gallery.

1 Answer
1

Attachments in a gallery are their own posts, with some special settings. To get a list of all the attachments for a given post, you basically just create a new query and specify the post parent and attachment type.

$gallery_images = new WP_Query(array(
    'post_parent' => $post->ID,
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'post_status' => 'inherit',
    )
);

You can then loop through this query in the same way as any other loop to access those images.

while ( $gallery_images->have_posts() ) : $gallery_images->the_post();
    the_title(); 
    the_content(); 
    the_permalink();
    whatever();
endwhile;

// always reset the post data at the end of any non-main loop
wp_reset_postdata();

Creating a text link to one of those images would be done the wp_get_attachment_link function. For a text only link, use “none” as the size parameter.

echo wp_get_attachment_link( $attachment_id, 'none', true, false, 'Link Text' );

Leave a Comment