Search code examples
wordpresswordpress-gutenbergwordpress-block-theme

Template for CPT (Block Themes)


I want to set for my CPT (ex. Book) a specific structure of blocks (ex. image, heading, paragraph). When the user creates a new post type Book it must see this structure in a post and have the ability to edit and publish it.

How I see the solution:

  1. Add template in register_post_type();
function myplugin_register_book_post_type() {
    $args = array(
        'public' => true,
        'label'  => 'Books',
        'show_in_rest' => true,
        'template' => array(
            array( 'core/image', array(
                'align' => 'left',
            ) ),
            array( 'core/heading', array(
                'placeholder' => 'Add Author...',
            ) ),
            array( 'core/paragraph', array(
                'placeholder' => 'Add Description...',
            ) ),
        ),
    );
    register_post_type( 'book', $args );
}
add_action( 'init', 'myplugin_register_book_post_type' );
  1. Add single-book.html template in the templates folder with this structure:
<!-- wp:image {"align":"left"} /-->
<!-- wp:heading {"placeholder":"Add Author..."} /-->
<!-- wp:paragraph {"placeholder":"Add Description..."} /-->

But when I publish a post I don't see anything on frontend. I tried to solve this by using reusable blocks and instead, my structure was something like <!-- wp:block {"ref":"51"} /-->

It works, but not the way as I need - every time, when I save my new post changes also rewrite my template and reusable block (https://github.com/WordPress/gutenberg/issues/29269)

I prefer my first solution, but what am I missing? Maybe I need to add somehow attributes to my template, can't find info in documentation.


Solution

  • I found the issue - I don't need to add in the template single-book.html the same block structure, as I use in register_post_type();

    I need just to add in single-book.html block <!-- wp:post-content /-->

    Now all works