Select Page

WordPress 3.5 introduced us to the new built-in Gallery system which is very nice I must say.

However if you’re a developer then you may have noticed that the old way of getting images associated with a post doesn’t return the images in the new Gallery system.

Why? The reason is simple.

The new Gallery system doesn’t associate the image to a post as an attachment and this means that you can’t perform a DB query to [codelet]get_posts()[/codelet] passing the [codelet]post_type[/codelet] as “attachment” and the [codelet]post_mime_type[/codelet] as “image”, as you would normally do.

Here’s how to get those Gallery images

The new solution is to search the post content for the Gallery shortcode and extract the list of IDs it uses.

When you create a new Gallery you will see a large control interface in the post editor.

Hovering over the Gallery shows two control buttons in the top left corner to edit and delete the Gallery.

However, WordPress stores this Gallery control as a shortcode in the post content like this

[codelet][ gallery link=”file” ids=”4374,4362″ ][/codelet]

I added spaces within the square brackets to stop WordPress trying to render the shortcode.

So you can see that the linking method is defined by the argument link and the IDs of all the images in the Gallery are held in the argument ids.

The Code

Add this code to your functions.php file.

[gist id=8142737 file=code-snippet-1.php]

Line 6: gets a list of all the WordPress shortcodes that have been defined within the system and returns them as a regular expression.
The gallery IDs are returned in an array number four if we’re running WordPress 3.5.x.

Line 10: checks to see if there are multiple galleries on the post

Lines 11-17: Loops through the regular expression matches for the IDs of the images and returns them in an array called [codelet]$id[/codelet].

You can now call the function [codelet]lc_grab_ids_from_gallery()[/codelet] in any of your PHP template files and get a list of image IDs from any Galleries on a WordPress post.