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.

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?

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

Comments are closed.

Keep In Touch With My Weekly Blog Email

A once-per-week daily digest of my posts from the week. No sales, no spam and I will not share your details with anyone else.


Wil is a dad, WordPress consultant, WordPress developer, business coach and mentor. He co-organizes the WordPress Sydney meetup group and has been on the organising committee for WordCamp Sydney since 2014. He speaks at many special events and contributes to the WordPress open source project. His likes are chillies, craft beer and electrogravitics.

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

Comments are closed.