Gutenberg block CSS does not apply to preview in template parts editor

1.2k Views Asked by At

I'm trying to add support for template parts to my WordPress theme.

I have a block with a stylesheet and a script and everything works fine. However, in the template part editor (Design -> Template parts), my styles are loaded but they don't apply to my block.

I've added the following CSS to my block's stylesheet just for testing:

* {
    outline: 1px solid red !important;
}

When editing the page (Pages -> (some page) -> edit), it works an every element gets a red border.

However, in the template part editor, it looks like this:

Screenshot of the template part editor. Every element has a red border except the elements in the preview box.

Here, the red border applies to all elements except the elements in the preview area - which means that my preview is not styled at all.

But this only affects the preview, on the normal website everything is styled properly.

I'm also adding a custom style tag using the enqueue_block_assets hook and this styling doesn't apply to the template part preview box either (but it does everywhere else).

What am I doing wrong?


Update

I created a plugin which does the exact same thing - and it works. Some more testing, and it looks like it doesn't work when the block is inside a theme.

// It works when I do this
register_block_type(ABSPATH . "/wp-content/plugins/<plugin_name>/header");

// But not when I do this
register_block_type(ABSPATH . "/wp-content/themes/<theme_name>/blocks/header");

// (both header folders are the exact same (plugin & theme))

But I need to have the block inside the theme, not the plugin. How can I achieve this?

2

There are 2 best solutions below

0
On BEST ANSWER

Fixed, the following line was missing:

add_editor_style(/* url to block css */);
1
On

The preview area is actually within an <iframe> that has inline styles and the theme & block styles loaded, which takes precedence over the * {...} style you've added, eg:

Editor Canvas

<iframe name="editor-canvas" tabindex="0" srcdoc="<!doctype html><style>html{height:auto!important;}body{margin:0}</style>...</iframe>

The hook you are looking for is enqueue_block_editor_assets if you just want to add Editor specific styles that don't affect the frontend.