WordPress block filters
Mark Howells-Mead edited this page Apr 12, 2024
·
3 revisions
/**
* Save the clientId and anchor attribute to the block attributes
* This is so that we can use these values in the frontend when
* parsing the blocks using parse_blocks.
*
* (The value of "anchor" is not saved to the database, so we're
* saving it as an additional custom attribute.)
*
* mark@sayhello.ch April 2024
*/
import { __ } from '@wordpress/i18n';
import { addFilter } from '@wordpress/hooks';
import { createHigherOrderComponent } from '@wordpress/compose';
const allowedBlocks = ['core/heading'];
addFilter('blocks.registerBlockType', 'shp/core-heading/block-attributes', (settings) => {
if (!allowedBlocks.includes(settings.name)) {
return settings;
}
return {
...settings,
attributes: {
...settings.attributes,
anchorBackup: {
type: 'string',
default: '',
},
clientId: {
type: 'string',
default: '',
},
},
};
});
addFilter(
'editor.BlockEdit',
'shp/core-heading/block-attributes',
createHigherOrderComponent((BlockEdit) => {
return (props) => {
const { attributes, name, clientId, setAttributes } = props;
const { anchor } = attributes;
if (!allowedBlocks.includes(name)) {
return <BlockEdit {...props} />;
}
setAttributes({
...attributes,
clientId,
anchorBackup: anchor,
});
return <BlockEdit {...props} />;
};
})
);
Mark Howells-Mead | https://permanenttourist.ch and https://sayhello.ch/ | Wiki since 2016
Use this code freely, widely and for free. Provision of this code provides and implies no guarantee.
Please respect the GPL v3 licence, which is available via http://www.gnu.org/licenses/gpl-3.0.html