How to modify an image block in Gutenberg WordPress 5?

After some digging and trial/error I have came up with a couple solutions. I was looking for a “Gutenberg” solution so I could avoid using str_replace.

First, we need to enqueue our JS and include the wp.blocks package

// Add to functions.php

function gutenberg_enqueue() {
    wp_enqueue_script(
        'myguten-script',
        // get_template_directory_uri() . '/js/gutenberg.js', // For Parent Themes
        get_stylesheet_directory_uri() . '/js/gutenberg.js', // For Child Themes
        array('wp-blocks') // Include wp.blocks Package             
    );
}

add_action('enqueue_block_editor_assets', 'gutenberg_enqueue');

Next, I found a couple solutions, the first is probably the best for your specific use-case.

Method #1

Use a filter function to override the default class. Well, in this case we are going to keep the “wp-block-image” class and just add the needed bootstrap class mt-2. But you could easily add whatever class you wanted. Add the code below and create a new image block, inspect it to see the figure tag now has the new class.

// Add to your JS file

function setBlockCustomClassName(className, blockName) {
    return blockName === 'core/image' ?
        'wp-block-image mt-2' :
        className;
}

wp.hooks.addFilter(
    'blocks.getBlockDefaultClassName',
    'my-plugin/set-block-custom-class-name',
    setBlockCustomClassName
);

Method #2

Add a setting in the block styles settings in the sidebar to add a class to the image.

// Add to your JS file

wp.blocks.registerBlockStyle('core/image', {
    name: 'test-image-class',
    label: 'Test Class'
});

enter image description here

This will add your class but unfortunately Gutenberg appends is-style- before the class, so it results in is-style-test-image-class. You would have to adjust your CSS accordingly.


Method #3

Manually adding the class via the Block > Advanced > Additional CSS Class option. Obviously, the class would need to be added for each image block.

enter image description here


Note: When adding or editing any of the JS above I needed to delete the block, refresh the page and then re-add the block to avoid getting a block validation error.

References:

Block Style Variations

blocks.getBlockDefaultClassName

Leave a Comment