The problem
I am currently working on a project where I have to give each Gutenberg block its own properties, such as a background image. I have created my own sidebar item for each block but the properties have not been saved.
I’ve searched the Internet for a long time for a solution but there was no clear explanation. That’s why I thought it would be important to share my learning with you, so you can use it immediately if you have the same issue.
The solution: Block Filters
Every attribute that has been assigned to a block element must already be specified when the block is registered. Subsequently added attributes are not saved. While these are taken over when the page is saved, if you then reload the backend, a validation error will be thrown and the corresponding blocks will not be rendered.
This problem can be solved by using the Gutenberg filter function. This gives you the ability to inject attributes to all desired blocks. In the following example I inject the attribute background_image for each block:
wp.hooks.addFilter('blocks.registerBlockType', 'custom/filter', function(blockOptions) {
if(blockOptions.hasOwnProperty('attributes')) blockOptions.attributes.background_image = {
type: 'string',
default: ''
};
return blockOptions;
});