Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.