WordPress Custom Source Block Bindings with Block Variations

This is a follow up to my first block bindings post, and Brian Coords great YouTube video.

Combining custom sources for block bindings with block variations can be a simple and powerful tool.

Here’s a straightforward example on how they can be beneficial together. With a block theme in the past if you wanted the copyright year in your site footer to stay up to date that would require a custom block which while not too much work, feels excessive, or installing a 3rd party plugin to provide the block which just adds another dependency out of your control.

Instead let’s register a custom block binding in our theme functions.php or a custom plugin to house the custom code for the website:

add_action('init', function() {
	register_block_bindings_source( 'namespace/current-year', array(
		'label'              => __( 'Current Year', 'namespace' ),
		'get_value_callback' => function(array $source_args, WP_Block $block_instance, string $attribute_name) {
			return date('Y');
		}
	) );
});	

You’d want to of course swap ‘namespace’ with your projects namespace

Next let’s register a block variation. Brian in the video above covers how to do it in PHP, but I’ll stick with JavaScript.

wp.blocks.registerBlockVariation(
	"core/paragraph", // The block type to register the variation for
	{
		name: "current-year", // The name of the variation
		title: "Current year", // The title of the variation
		icon: "clock", // The icon to use for the variation
		description:
			"Dynamic block that displays the current year on the frontend of the website",
		attributes: {
			// The default attributes for the variation
			className: "current-year",
			content: "YYYY",
			metadata: {
				bindings: {
					content: {
						source: "namespace/current-year",
					},
				},
			},
		},
		isActive: ({ className }) => {
			if (className === undefined) return null;
			return className.includes("current-year") ? true : null;
		},
	},
);

That does it. Now in the inserter you have what appears to be a custom block called ‘Current Year’ that inserts ‘YYYY’ into the editor, but on the frontend gets rendered as the current year by using date(‘Y’);

I’m using this same technique for breadcrumbs, and I’m sure there’s plenty of other use cases as well.