I am developing a WordPress theme that uses Gutenberg blocks. I have created a custom block that has its own stylesheet and script. The block works fine on the front-end and the page editor, but it does not display correctly on the template part editor.
The template part editor is a new feature in WordPress that allows me to create reusable parts of my theme, such as headers and footers. I can access it from Design -> Template parts in the dashboard.
The problem is that when I preview my custom block in the template part editor, it does not apply the styles from the stylesheet. I have tried adding a simple CSS rule to test it:
This rule should add a red border to every element on the page. It works on the front-end and the page editor, but not on the template part editor. The preview area does not show any red border at all.
I have also tried adding a custom style tag using the enqueue_block_assets hook, but it does not work either. The style tag is loaded on the template part editor, but it does not affect the preview area.
I don’t understand why this is happening. Is there something special about the template part editor that prevents it from applying the styles to the preview area? How can I fix this issue and make my custom block look consistent on all editors?
Thank you for your help.
Hello,
I have encountered a similar issue with my custom blocks and the template part editor. After doing some research, I found out that the template part editor uses a different iframe than the page editor to render the preview area. This means that the styles from the parent document are not inherited by the iframe.
To solve this problem, you need to add your stylesheet and script to the template part editor iframe as well. You can do this by using the enqueue_block_editor_assets hook, which is fired when the block editor assets are enqueued for both the page editor and the template part editor.
Here is an example of how to use this hook in your functions.php file:
function my_custom_block_enqueue_assets() {
// Register and enqueue your stylesheet and script for your custom block
wp_register_style( ‘my-custom-block-style’, get_template_directory_uri() . ‘/css/my-custom-block.css’ );
wp_enqueue_style( ‘my-custom-block-style’ );
wp_register_script( ‘my-custom-block-script’, get_template_directory_uri() . ‘/js/my-custom-block.js’, array( ‘wp-blocks’, ‘wp-element’ ) );
wp_enqueue_script( ‘my-custom-block-script’ );
}
add_action( ‘enqueue_block_editor_assets’, ‘my_custom_block_enqueue_assets’ );
This should make your custom block display correctly on both the page editor and the template part editor. I hope this helps you with your WordPress theme development.
Best regards,