Add additional scripts and markup in the section of default Gutenberg theme

If The Goal Is Adding It When a Block Is Used

WP will automatically add JS if you specify the file in block.json, specify a viewScript and it will register and enqueue that script when the block is used ( and only when it’s used ). Likewise for CSS you can specify style.

Both take a string or array, e.g.

{ "style": [ "file:./style.css", "example-shared-style" ] }

Here style.css is relative to the location of block.json.

You can also use PHP filters to modify the markup at runtime, even for blocks that don’t use server rendering.

If you need to add something other than JS or CSS to the <head> tag though, then you’ll need to use the wp_head action.

If The Goal Is Adding Arbitrary HTML To The Header

There are several reasons:

1. header.html is a block template, not the <head>

Unlike a classic theme, the <html> <body> <head> etc tags don’t appear inside the block templates because they aren’t block content. Instead they’re managed by WordPress using hooks and filters. If you want to modify these areas you need to use hooks and enqueue things, which is how you were meant to do it in classic non-block themes too, except it was easier to be bad and hardcode things.

So you can’t modify <head> via a block template, and you’re not supposed to.

Even in a classic theme this would be a bad idea as there are dedicated APIs for doing this, hardcoding should always be a last resort.

Consider inserting code the official normal way instead of hardcoding it, like you would in a classic theme, wp_add_inline_script/wp_enqueue_script/etc, or if you really must hardcode it the wp_head hook.

2. Even if You Could Do It Directly in a Block Theme HTML File, script tags etc would get stripped out

Because you’re not supposed to put them there.

For the same reason you can’t embed them directly in post content. You’re not meant to put script tags directly into content, you’re meant to insert blocks/widgets/shortcodes that generate script tags at runtime. It’s a security thing.

3. Even if you Could Do The Above Two..

WP probably won’t read your HTML file, because block templates are starting points, and you’ve probably modified it in the site editor, so WP will prefer the template post in the database instead, even if you modify the theme.

To get around that you can revert back to the theme in the site editors template list, but it won’t be much use here since problems 1 and 2 still apply.

The TLDR

Don’t do that, it’s a bad idea even in a classic theme. Instead use the standard APIs for enqueing scripts and inserting inline scripts, and wp_head for arbitrary HTML tags.