ryanwelcher
5/14/2019 - 6:00 PM

Dynamically Assign Templates In Gutenberg

Dynamically Assign Templates In Gutenberg

<?php
/**
 * Defines the block templates.
 *
 * @todo add references to the custom blocks
 *
 * @return array
 */
function get_block_templates() {
	return [
		'template_one' => [
			'name'   => 'Template One',
			'blocks' => [
				[
					'core/image',
					[
						'align' => 'right',
					],
				],
				[
					'core/paragraph',
					[
						'placeholder' => 'Natoque iure necessitatibus rhoncus nisl aut incidunt pellentesque torquent nonummy voluptatibus posuere maecenas illo nunc fugiat, laboriosam quas facilisis ea, orci? . Dolorum aenean dolor, corporis laborum! ',
					],
				],
				[ 'core/image' ],
			],
		],
		'template_two' => [
			'name'   => 'Template Two',
			'blocks' => [
				[
					'core/paragraph',
					[
						'placeholder' => 'Natoque iure necessitatibus rhoncus nisl aut incidunt pellentesque torquent nonummy voluptatibus posuere maecenas illo nunc fugiat, laboriosam quas facilisis ea, orci? . Dolorum aenean dolor, corporis laborum! ',
					],
				],
				[ 'core/image' ],
			],
		],
	];
}


/**
 * Add the new menu item.
 */
add_action( 'admin_menu', 'insert_new_items_admin_menu' );
function insert_new_items_admin_menu() {
	$templates = get_block_templates();
	foreach ( $templates as $slug => $details ) {
		/*
		 * Translators: Call to action to create a new story from a template.
		 */
		$name = sprintf( __( 'Add New From %s Template' ), $details['name'] );
		add_submenu_page(
			'edit.php?post_type=post',
			$name,
			$name,
			'edit_posts',
			'post-new.php?post_type=post&template=' . $slug
		);
	}
}
/**
 * Insert the chosen template.
 */
add_action( 'init', 'insert_template' );
function insert_template() {
	$template  = isset( $_GET['template'] ) ? wp_unslash( $_GET['template'] ) : false;
	$templates = get_block_templates();
	if ( $template && array_key_exists( $template, $templates ) ) {
		$story_object           = get_post_type_object( 'post' );
		$story_object->template = $templates[ $template ]['blocks'];
	}
}