Let's say contains a core/gallery block inside which I want to render on my own. How can I get the gallery ID or the Image IDs in the server-side render.php?


const { Gallery, InspectorControls, InnerBlocks } = wp.blockEditor;
const { registerBlockType } = wp.blocks;
const { Button, PanelBody, TextControl } = wp.components;
const ALLOWED_BLOCKS = ['core/gallery'];

const MY_TEMPLATE = [
    ['core/gallery', { placeholder: 'Gallery' }],

registerBlockType('my-gallery-block/main', {
    title: 'My Gallery',
    icon: 'dashicons-format-gallery',
    category: 'my-blocks',
    attributes: {
        htmlId: {
            type: 'string'
        galleryIds: {
            type: 'string'
    edit({ attributes, className, setAttributes }) {

        return (<div>
            <div className="button-container">
                Gallery Block
                        label="HTML ID"
                        onChange={(content) => setAttributes({ htmlId: content })}
    save() {
        return (<InnerBlocks.Content />);


<?php function render_gallery_block( $attributes, $content ) {

// How do I get the gallery ID or the Image IDs within the gallery?

    $output = ob_get_contents(); // collect output
    ob_end_clean(); // Turn off ouput buffer
    return $output; // Print output      

I know that the $content variable already contains the rendered Gallery block as a HTML string, but I would like to avoid extracting the Image URLs from the HTML string if possible.

Does anyone know a better way?


Using the render_block filter (as opposed to wrapping the block with your custom block) is a simpler way to accomplish what you want. The filter runs for all blocks so you have to conditionally apply your logic to just the blocks you want. The attributes of each block will be available ($block[attrs]) and for the current core/gallery block the images attribute would have the data you want.

Something to watch out for is that the Gallery block is migrating to use nested Image blocks and will no longer keep a list of the images in an attribute of its own. That's coming up in the 5.9 release.

Even then the render_block filter can be used for this but instead of checking the block attributes you'd iterate through $block['innerBlocks'] to get the image ids.

In case it helps here's starter snippet, with a rudimentary condition to affect only gallery blocks with a specific class.

add_filter( 'render_block', function ( $block_content, $block ) {
    if (
        $block['blockName'] === 'core/gallery'
        && $block['attrs']['className'] === 'is-rad'
    ) {
        // $block also has 'innerBlocks'
        $block_content = 'whiz bang';
    return $block_content;
}, 10, 2 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.