How to parse a WordPress gallery block and return image IDs

Ciprian on Tuesday, May 31, 2022 in WordPress

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

WordPress Gallery Block
WordPress Gallery Block

Lots have changed in the past years in relation to WordPress gallery blocks.

My eCard plugin relies on parsing these gallery blocks for its eCard Collection feature. Before WordPress 5.9, I could use the parse_blocks() function to get the gallery images IDs.

This function converts the HTML comments and markup stored in post_content into an array of parsed block objects.

WordPress 5.9+ has a different Gutenberg version (11.9), so the structure of the parse block has changed.

One of the method that works, if you need image URLs, is the get_post_galleries() function, which returns a list of arrays, each containing gallery data and sources parsed from the expanded shortcode. It doesn’t return IDs, though, and this is what I require, and I think it’s the most important value to be returned.

So, here’s my approach:

First, I get the content of the post:

$post_content = get_post_field( 'post_content', $post_id );

Next, I am checking for a gallery block:

if ( has_block( 'gallery', $post_content ) ) {
    // If there is a gallery block (block editor)
}

Next, I am parsing the blocks and looping through the array to get all image IDs:

if ( has_block( 'gallery', $post_content ) ) {
    // If there is a gallery block (block editor)
    $post_blocks = parse_blocks( $post_content );

    $post_blocks_array = $post_blocks[0]['innerBlocks'];

    foreach ( $post_blocks_array as $post_block ) {
        $id_array[] = $post_block['attrs']['id'];
    }
}

And that is everything, my $id_array variable now contains a simple array of numerical IDs.

Related posts

Leave a Reply

You have to agree to the comment policy.