How to get Gallery Images in WordPress 3.5

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 get_posts() passing the post_type as “attachment” and the post_mime_type 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.

WordPress 3.5 Gallery

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

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

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 $id.

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

Was this article helpful?
YesNo

1 thought on “How to get Gallery Images in WordPress 3.5”

Comments are closed.