How can I add a custom attribute to Gutenberg core blocks?

I’m trying to add a dropdown to WordPress core blocks to select a data attribute that will be added to the front-end (e.g. data-attr=”value-from-dropdown”).

I think the solution is to add a custom attribute to the core blocks, set it in the back-end and pass it to the front-end, but I can’t for the life of me figure out how to add a new attribute to a core block. This here is the closest I’ve gotten, but this just lets me create a dropdown, running props.setAttribute() inside doesn’t work.

https://wordpress.org/gutenberg/handbook/extensibility/extending-blocks/#editor-blockedit

Is there anything I can do, or is the functionality just not there yet?

2 s
2

You can add a custom attribute to any registered block by using the blocks.registerBlockType filter.

/**
 * Filter the attributes for all blocks to add custom ones
 *
 * Name can be used to only add the new attribute to a certain block.
 *
 * @param settings
 * @param name
 * @returns {*}
 */
function addCustomAttributes( settings, name ) {
    if ( settings.attributes ) {

        settings.attributes.customAttribute = {
            type: 'string',
            default: ''
        };

        settings.attributes.anotherCustomAttribute = {
            type: 'boolean',
            default: false
        };
    }
    return settings;
}

addFilter( 'blocks.registerBlockType', 'namespace/filterBlockAttributes', addCustomAttributes );

Leave a Comment