Search code examples
wordpresshookwordpress-gutenberg

Add custom class to Wordpress Gutenberg Gallery block


I would like to automatically add a class to a standard Gutenberg gallery block named 'custom-class' so I don't have to add this manually every time I create a new gallery.

Is this possible via a hook in functions.php?

My attempt doesn't work...

function add_custom_class_to_gallery_block($settings)
{
    if (isset($settings['blockSettings']['core/gallery']['attributes']['className'])) {
        $settings['blockSettings']['core/gallery']['attributes']['className'] .= ' custom-class';
    } else {
        $settings['blockSettings']['core/gallery']['attributes']['className'] = 'custom-class';
    }
    return $settings;
}

add_filter('block_editor_settings', 'add_custom_class_to_gallery_block');

Solution

  • A filter can be applied to a target a specific Gutenberg block with render_block_{$this->name} where the first parameter is the $block_content string (HTML markup). Without affecting the Editor classes or validation of the markup saved, a simple string replacement can be used on the $block_content string to add the class before WP_Block->render() is called, eg:

    <?php
    
    function add_custom_class_to_gallery_block($block_content)
    {    
        // Simple string replacement
        $block_content = str_replace('wp-block-gallery', 'wp-block-gallery custom-class', $block_content);
        
        // Returns altered $block_content to be rendered
        return $block_content;
    }
    
    // Add filter only to 'core/gallery' block
    add_filter('render_block_core/gallery', 'add_custom_class_to_gallery_block');