Last active
July 19, 2022 09:50
-
-
Save ryanwelcher/301b62f918bc2d053d0629d697f6b9bd to your computer and use it in GitHub Desktop.
Dynamically Assign Templates In Gutenberg
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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']; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment