Skip to content

WordPress block filters

Mark Howells-Mead edited this page Apr 12, 2024 · 3 revisions

Add preset image size selector to post featured image block

Save the heading block's clientId as a block attribute

/**
 * 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} />;
		};
	})
);
Clone this wiki locally