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( "https://wordpress.stackexchange.com/". $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…
- grab the regex that Core uses to extract shortcodes
- If there is a shortcode, parse the attributes
- Grab the first ID and get the image ( or try
get_attachment_image_url()
if more convenient )