Skip to content

Instantly share code, notes, and snippets.

@zgordon
Last active January 7, 2024 05:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save zgordon/a7ea4f9348ee72c5493f6eeeab54b76d to your computer and use it in GitHub Desktop.
Save zgordon/a7ea4f9348ee72c5493f6eeeab54b76d to your computer and use it in GitHub Desktop.
Example of how to add block templates to post types in WordPress
<?php
function mytheme_block_templates( $args, $post_type ) {
// Only add template to 'post' post type
// Change for your post type: eg 'page', 'event', 'product'
if ( 'post' == $post_type ) {
// Optionally lock templates from further changes
// Change to 'insert' to allow adding other blocks, but lock defined blocks
$args['template_lock'] = 'all';
// Set the template
$args['template'] = [
[
// Example of including a core image block
// Optional alignment setting
'core/image', [
'align' => 'left',
]
],
[
// Example of including a core paragraph block
// Optional alignment placeholder setting
'core/paragraph', [
'placeholder' => 'The only thing you can add',
'align' => 'right',
]
],
[
// Example of including a custom block
// Optional placeholder setting
'custom/your-blocks', [
'placeholder' => 'Custom placeholder',
]
]
];
}
return $args;
}
// Hook function into post type arguments filter
add_filter( 'register_post_type_args', 'mytheme_block_templates', 20, 2 );
Copy link

ghost commented Jan 13, 2022

Awsome!
Thanks for this good exemple :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment