WordPress 5.6 kommt mit einer neuen Block-API-Version, die es Blöcken ermöglicht, ihr eigenes Block-Wrapper-Element zu rendern. Dadurch wird es möglich, das Block-Markup im Editor dem im Frontend ähnlicher zu machen, wodurch das Styling der Editor-Ansicht vereinfacht wird.

Die neue API-Version freischalten

Die API ist nicht standardmäßig aktiv, sondern muss pro Block aktiviert werden. Dazu wird in dem Konfigurations-Objekt in registerBlockType der Wert für apiVersion auf 2 gesetzt:

registerBlockType( slug/name, { apiVersion: 2 } );

edit– und save-Funktion anpassen

Das Wrapper-Element des Blocks muss in der neuen API-Version mit useBlockProps markiert werden, das sowohl in der edit– als auch save-Funktion des Blocks zum Einsatz kommt.

Im folgenden Code-Block wird ein kleiner Block mit der neuen API-Version registriert, der im Editor lediglich ein Feld für Text anzeigt.

const {
	registerBlockType,
} = wp.blocks;
const {
	RichText,
	useBlockProps,
} = wp.blockEditor;

registerBlockType( 'slug/name', {
	title: 'Block title',
	category: 'widgets',
	attributes: {
		text: {
			type: 'string',
			default: '',
		},
	},
	apiVersion: 2,
	edit: ( { attributes, setAttributes } ) => {
		const {
			text,
		} = attributes;
		
		const blockProps = useBlockProps(
			{
				className: 'wp-block-slug-name',
			}
		);

		return (
			<‎RichText
				value={ text }
				onChange={ ( text ) => setAttributes( { text } ) }
				placeholder='Placeholder text'
				{ ...blockProps }
			/>
		);
	},
	save: ( { attributes } ) => {
		const {
			text,
		} = attributes;
		
		const blockProps = useBlockProps.save(
			{
				className: 'wp-block-slug-name',
			}
		);

		return <p { ...blockProps }>{ text }</p>;
	}
} );
Code-Sprache: JavaScript (javascript)

Die spezifischen Teile für die neue API-Version sind die folgenden:

Durch die Umstellung auf die API-Version 2 erreichen wir in dem konkreten Beispiel, dass das p-Element des Eingabefeldes im Editor gleichzeitig auch das Wrapper-Element mit der Klasse wp-block-slug-name ist, statt wie sonst ein umliegendes div. In dem Fall haben wir also sehr ähnliches Markup im Editor und Frontend.