How to insert gutenberg block inside post_content when using wp_insert_post()?
When you manually add a YouTube block, click the "Code Editor" view in the Tools & Options menu (right side). In the Code Editor view you will see the HTML needed for the editor to correctly parse the block.
For example:
<!-- wp:core-embed/youtube {"url":"https://www.youtube.com/watch?v=VIDEOID","type":"video","providerNameSlug":"youtube","className":"wp-embed-aspect-16-9 wp-has-aspect-ratio"} --><figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">https://www.youtube.com/watch?v=VIDEOID</div></figure><!-- /wp:core-embed/youtube -->
Today I had to update programmatically the content of Gutenberg blocks.
I used two methods:
parse_blocks()
to read the existing array, which I could modify as any array in PHP.render_blocks()
to then add the content to the post post_content;the post array can then be saved viawp_update_post()
.
Reading this article was helpful https://www.billerickson.net/access-gutenberg-block-data/
My own project involved editing relationship act fields to other custom post types within blocks but process should be fairly similar. Regarding OP's project: I would suggest to have a first post done manually to generate the template for an array (parse_block). Then customising this array should be relatively trivial.