Support » Developing with WordPress » Programmatically add Gutenberg blocks to edit post page

  • Resolved vgz



    I want to add some kind of “required blocks” to a custom post type. If they are missing (e.g. if you create a new post, or on save), they should get added to the post, on load before the rendering so it is instantly there.

    I’ve tried to add blocks to the Gutenberg editor per php. But I don’t even have found a filter which lets me edit the post content before it gets rendered. But even if there is such a hook, I would need to know the block html markup to add it to the content.

    With “has_blocks()” and “parse_blocks()” I way able to check if blocks are missing in the “the_post” action. But how can I get a registered block and add it to the post content – before the post gets rendered in the admin view / Gutenberg Editor?

Viewing 3 replies - 1 through 3 (of 3 total)
  • hello VGZ,

    You may find this link helpful.

    Best Regards,
    Syed H

    Thread Starter vgz


    Hey syhussaini,

    thanks! Will have a look at this, but at first sight it’s about creating blocks, not automatically adding blocks into the content.

    Meanwhile I’ve got this to work by myself, but it’s a bit hacky. I use the “the_post” and the “save_post” actions with low priority, so I am able to parse the content for blocks before the edit page gets rendered. Missing blocks get added to the post with wp_update_post() by adding the block template like it is stored in the database (just the block as string).

    Besides that, I am adding blocks with JS – this is needed if a new post gets created. When wp.domReady gets called I create a block with wp.blocks.createBlock() and insert it with‘core/editor’).insertBlocks().

    This way missing blocks get added when a new post is created, or an existing post is edited or saved.

    Best regards,

    • This reply was modified 2 years, 2 months ago by vgz.


    another possible approach is using default_content filter to pass gutenberg a template.

    The template look something like

    <!-- wp:paragraph {"placeholder":"Add Description"} -->
    <!-- /wp:paragraph -->

    just save an empty form and you have your template

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Programmatically add Gutenberg blocks to edit post page’ is closed to new replies.