I'm currently in the process of creating my first custom wp theme, in which the post contains the title, the content, the gallery, and also a div in between the title and content where as a background image I'd set the first image for the gallery below. I have tried using tons of different codes to get the first image from the gallery. Most versions of catch_that_image only work good on normal images, but not on galleries. I have tried using the function from THIS POST. It caught the first image good, but destroyed the sites gallery (no idea how it happened, new to this stuff).

Does anybody know a good way to find the first image of a gallery? Also I'd really appreciate an easy to get explanation. I'm really a 'just arrived' person here, trying to not go crazy.

Using the latest Wordpress version.

1 Answer 1


The gallery is a shortcode, so you will need to parse the shortcode to grab the image referenced therein:

function pull_image_from_gallery(){
  global $post;
  $pattern = get_shortcode_regex();
  preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches );
  foreach ($matches[2] as $k=>$v) {
    if ('gallery' == $v) {
      $atts = shortcode_parse_atts($matches[3][$k]);
      if (!empty($atts['ids'])) {
        $ids = explode(',',$atts['ids']);
        $first = $ids[0];
        $image = wp_get_attachment_image_src( $atts['ids'] );
        if (!empty($image)) {
          // do what you want with image
          return $image[0];

I think the code is fairly easy to follow but...

  1. grab the regex that Core uses to extract shortcodes
  2. If there is a shortcode, parse the attributes
  3. Grab the first ID and get the image ( or try get_attachment_image_url() if more convenient )
  • Thanks for your answer but the code didnt work. I have pasted it into functions and used <img src="<?php pull_image_from_gallery(); ?>" alt="first gallery image"/> But it only returned the alt text.
    – aln447
    Commented Oct 30, 2015 at 16:04
  • My code doesn't return or echo anything. You are using it wrong. See the part where it says `do what you want with image"? That is the part you have to fill in.
    – s_ha_dum
    Commented Oct 30, 2015 at 16:37
  • Oh yeah, sorry. Like I said I'm new to this junk
    – aln447
    Commented Oct 30, 2015 at 16:52
  • @aln447 : see the edit. I made changes to fit the way you are trying to use it. Make sure you re-copy the whole thing.
    – s_ha_dum
    Commented Oct 30, 2015 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.