I had the same issue and was previously using get_children()
to retrieve the top 4 images from a gallery for a given page.
Here’s the solution I came up with:
// helper function to return first regex match
function get_match( $regex, $content ) {
preg_match($regex, $content, $matches);
return $matches[1];
}
// Extract the shortcode arguments from the $page or $post
$shortcode_args = shortcode_parse_atts(get_match('/\[gallery\s(.*)\]/isU', $post->post_content));
// get the attachments specified in the "ids" shortcode argument
$attachments = get_posts(
array(
'include' => $shortcode_args["ids"],
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'menu_order ID',
'orderby' => 'post__in', //this forces the order to be based on the order of the "include" param
'numberposts' => 1,
)
);
Now, 'numberposts' => 1
above doesn’t seem to work when you specify more than one id in the include parameter. So, you have a couple of choices:
- Explode the “ids” argument and grab only the first ID for use in your get_posts call
- Grab only the first attachment returned from get_posts (but you’ll still be retrieving all attachments in the gallery). Not ideal, but will work.
Hope that helps!