Development WordPress

How to Run Code When the Block Editor Initializes (Gutenberg)

When you want to run some code right after the Block Editor / Gutenberg initializes, the documentation provides little to no clues on how to do this.

Here are 2 ways you can run your code right after the Block Editor initializes.

Method 1

The block editor calls initializeEditor to start the editor and stores the returned Promise in window._wpLoadBlockEditor. We can use that to put our logic that we want to run right after the editor starts.

Method 2

This method takes advantage of the registerPlugin method provided by the Block Editor.

We register our own plugin, and then the code is ran once and render nothing.

I’m not too sure about whether this would run once since technically the plugin is a Component, so it might get reused / rerun somehow. so I added a useEffect method to make sure it’s only called once.

By Benjamin Intal

Benjamin is an avid WordPress plugin developer, a full-stack developer, owner and lead developer of Gambit, founder of Stackable Blocks, Page Builder Sandwich, and creator of more than 30 WordPress plugins in CodeCanyon.

Connect with me on Twitter @bfintal

2 replies on “How to Run Code When the Block Editor Initializes (Gutenberg)”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.