0

I've created a default template for a CPT for example...

// Define template
$template = [
    [
        'core/heading',
    ],
];

// Register the CPT
register_post_type(
    'my_cpt',
    [
        // ...
        'template' => $template,
        // ...
    ]
);

If I go into WP Admin and click new then the block editor is pre-populated with a heading block. However if I create a post programmatically in PHP...

//
$post_data = [
    'post_status' => 'draft',
    'post_title'  => 'Test post',
    'post_type'   => 'my_cpt',
];

//
return wp_insert_post( $post_data, false );

The post has no content.

Is there some way I can make this work? I don't see a way of reusing my template. I can set post_content with parsed block data from the editor but I don't know how to convert my template into actual blocks. I'd rather not have to manage the template in multiple places so reuse is key

2
  • Not posting this as an answer because I’m not 100% certain, but I highly doubt it’s possible. PHP has no awareness of how to create most blocks. That markup is generated in the editor with JavaScript, so the server can’t use the post type template to populate the content with blocks. The only really solution is to insert the post with the final HTML of blocks that match the template. Nov 22, 2022 at 15:43
  • 1
    the template is a hint to the block editor, but if you create a post using code then there is no block editor JS app involved, your template won't be inserted unless you yourself manually and explicitly insert the same blocks in the post content when you insert it
    – Tom J Nowell
    Nov 22, 2022 at 15:52

0

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.

Browse other questions tagged or ask your own question.