1

I'm using WordPress 6.0 and I've created a child theme from TwentyTwentyTwo. I've created a custom post type using code like this:

register_post_type('foobar', [
   'public' => true,
   'show_in_rest' => true, // enable block editor
   // etc
]);

In my child theme, I've created the directory templates, and within it, a file named foobar.html. I've copied the contents of single.html from twentytwentytwo/templates/ to this folder and renamed it to foobar.html to make it match the custom post type.

If I open the site editor, and click "Templates", I see these templates listed:

  • Single Post
  • Page
  • foobar
  • Home
  • Search
  • etc...

However, when I create a new post of the custom post type foobar using the WordPress admin interface, the default template is "Default template", and not "foobar". How do I change the default block template for a custom block type?

1 Answer 1

1

Classic and block(-based) themes both use the same template hierarchy, so for example in classic themes, we can add a template named single-<post type>.php which would be used as the default template for displaying single posts in a specific post type, and in block themes, the equivalent template is named single-<post type>.html, but that template must be placed in the templates directory (e.g. at wp-content/themes/your-theme/templates) as opposed to the theme's root directory in classic themes.

So you should rename your template to single-foobar.html and WordPress will automatically load it on single post pages in the foobar post type, e.g. at https://example.com/foobar/foo-1/.

However, to make it appear as the "Default template", e.g. in the "Post tab → Template panel" in the block editor's sidebar, you need to register the template as a default template using the default_template_types hook:

add_filter( 'default_template_types', 'my_theme_default_template_types' );
function my_theme_default_template_types( $template_types ) {
    $template_types['single-foobar'] = array(
        'title'       => 'Single Foobar',
        'description' => 'Displays a single foobar post.',
    );

    return $template_types;
}

Preview (WordPress v6.0.1):

Preview image

So I hope that helps and you should check the Differences and similarities between classic themes and block themes, and you might also want to learn about registering custom templates: (which in classic themes, they use a header line, i.e. a PHP comment like Template Name: Foobar)

1
  • 1
    Thank you! That worked a treat. It was hard to find advice online for block themes as opposed to classic/legacy themes. This gave me the missing pieces.
    – Flimm
    Jul 16, 2022 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.