2

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?

EinLinuus
  • 625
  • 5
  • 16

2 Answers2

2

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.

S.Walsh
  • 3,105
  • 1
  • 12
  • 23
  • Thanks for the reply. I did some more testing and updated my question - the CSS works, but it's not loaded by Gutenberg in the full site editing preview. It works if I do the exact same thing but inside a plugin (see updated question). – EinLinuus Apr 05 '23 at 06:36
2

Fixed, the following line was missing:

add_editor_style(/* url to block css */);
EinLinuus
  • 625
  • 5
  • 16