Default Block Template for a Custom Post Type
Registers a block template from code, such as "Single Event", that block themes use automatically for a custom post type, so new post types look right without building the template by hand.
Opens WPIDE on
Code
// Post type that gets the template.
$wpide_template_post_type = 'event';
add_action( 'init', function () use ( $wpide_template_post_type ) {
if ( ! function_exists( 'register_block_template' ) ) {
return;
}
$object = get_post_type_object( $wpide_template_post_type );
register_block_template( 'wpide//single-' . $wpide_template_post_type, array(
'title' => 'Single ' . ( $object ? $object->labels->singular_name : ucfirst( $wpide_template_post_type ) ),
'description' => 'Layout for a single ' . $wpide_template_post_type . '.',
'content' => '<!-- wp:template-part {"slug":"header","tagName":"header"} /-->
<!-- wp:group {"tagName":"main","layout":{"type":"constrained"},"style":{"spacing":{"padding":{"top":"var:preset|spacing|50","bottom":"var:preset|spacing|50"}}}} -->
<main class="wp-block-group">
<!-- wp:post-title {"level":1} /-->
<!-- wp:post-date /-->
<!-- wp:post-featured-image {"aspectRatio":"16/9"} /-->
<!-- wp:post-content {"layout":{"type":"constrained"}} /-->
<!-- wp:post-terms {"term":"category"} /-->
</main>
<!-- /wp:group -->
<!-- wp:template-part {"slug":"footer","tagName":"footer"} /-->',
) );
}, 20 );
Notes
Needs WordPress 6.7+ and a block theme; set the post type slug and edit the block markup. A template saved in the Site Editor overrides this one.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.