Skip to content

Instantly share code, notes, and snippets.

@LinzardMac
Last active November 9, 2015 18:25
Show Gist options
  • Save LinzardMac/7a3d7be5a866e03131d3 to your computer and use it in GitHub Desktop.
Save LinzardMac/7a3d7be5a866e03131d3 to your computer and use it in GitHub Desktop.
Get a specified number of images in a post's gallery by post ID
function get_first_images($post, $count){
$post = get_post($post);
if ( ! has_shortcode( $post->post_content, 'gallery' ) ){
return array();
}
$galleries = array();
// find and separate out what kind of shortcode we are looking at
if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
foreach ( $matches as $shortcode ) {
if ( 'gallery' === $shortcode[2] ) {
$srcs = array();
$gallery_img_ids = $shortcode[3];
preg_match_all('/([0-9]+)/', $gallery_img_ids, $foundMatches);
$img_ids = $foundMatches[0];
if ( ! empty( $img_ids ) ) {
$i = 0;
foreach ( $img_ids as $img ){
$i++;
$gallery_image = wp_get_attachment_image_src(intval($img), 'thumbnail');
$srcs[] = $gallery_image[0];
if($i==$count) break;
}
}
return $srcs;
}
}
}
}
// pass post ID and how many images you want to get
$gallery_imgs = get_first_images( $pid, 4);
if ($gallery_imgs) {
foreach ($gallery_imgs as $img) {
echo '<img src="'. $img.'"/>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment