WordPress block filters - markhowellsmead/helpers GitHub Wiki

Code examples

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.)
 *
 * [email protected] 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} />;
		};
	})
);

Remove template part block wrapping DIV

<?php

namespace SayHello\Theme\Blocks\TemplatePart;

use DOMDocument;

/**
 * Template Part block
 *
 * @author Say Hello GmbH <[email protected]>
 */
class Block
{

	public function run()
	{
		add_action('render_block', [$this, 'renderBlock'], 10, 2);
	}

	/**
	 * This removes the wrapping DIV from all template part blocks
	 *
	 * @param string $html
	 * @param array $block
	 * @return string
	 */
	public function renderBlock(string $html, array $block)
	{

		if (empty($html) || $block['blockName'] !== 'core/template-part') {
			return $html;
		}

		if (mb_detect_encoding($html, 'UTF-8', true) === false) {
			return $html;
		}

		libxml_use_internal_errors(true);

		$document = new DOMDocument();
		$document->loadHTML($html);
		$wrapper = $document->documentElement->childNodes[0]->childNodes[0];

		// Make sure that the wrapper contains the standard template part class name
		if (strpos($wrapper->getAttribute('class'), 'wp-block-template-part') === FALSE) {
			return $html;
		}

		$document_out = new DOMDocument();

		foreach ($wrapper->childNodes as $child) {
			$document_out->appendChild($document_out->importNode($child->cloneNode(true), true));
		}

		return $document_out->saveHtml();
	}
}