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.

Related posts

Leave a Reply

1 comment

  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' );