Hey visitors! If you’re a beginner in WordPress and WP-CLI development, then you should check out my dear friend Bhargav’s Youtube channel! @BuntyWP

Toggling the block inserter programmatically in WordPress Gutenberg

Experimenting with the UX side of Web development, I was wondering if it was possible for the block inserter to be open by default on page load? Turns out, there is a way and it’s simple.

Let’s create a simple goal for the sake of learning –

Goal: Create a Gutenberg plugin that sets the Block Inserter to be open by default on page load.

Register a Gutenberg plugin

Since our goal does not render anything, a plugin would be best suited for the task.

import { registerPlugin } from "@wordpress/plugins";

function BlockInserterDefaultOpen() {
    return null;
}

registerPlugin( 'block-inserter-default-open', {
    render: BlockInserterDefaultOpen
} );

Code language: JavaScript (javascript)

For now, our plugin accepts a Component <BlockInserterDefaultOpen /> which itself doesn’t render anything. This component will hold the logic to display the block inserter on page load.

Add logic to display Block Inserter on page load

The Block Inserter state is part of Gutenberg’s Editor UI data stored in the core/edit-post data store.

To retrieve the current state of the inserter, we will use the selector isInserterOpened and to set the inserter’s state value, we will use the setIsInserterOpened action.

import { registerPlugin } from "@wordpress/plugins";
import { useSelect, useDispatch } from "@wordpress/data";
import { useEffect } from "@wordpress/element";

function BlockInserterDefaultOpen() {

    /**
     * `isInserterOpen` will hold the inserter's state value.
     */
    const { isInserterOpen } = useSelect( select => {
        return {
            isInserterOpen: select( 'core/edit-post' ).isInserterOpened(),
        }
    }, [] );

    const { setIsInserterOpened } = useDispatch( 'core/edit-post' );

    useEffect( () => {
        /**
         * If inserter is not open on page load, then open.
         *
         * Notice that we've passed an empty array as a dependency
         * to useEffect(), so that useEffect only runs once, i.e.;
         * on page load.
         */
        if ( ! isInserterOpen ) {
            setIsInserterOpened( true );
        }
    }, [] );

    return null;
}

registerPlugin( 'block-inserter-default-open', {
    render: BlockInserterDefaultOpen
} );

Code language: JavaScript (javascript)

That’s it. Now, whenever we open a post to edit, the Block Inserter will be open by default. Go ahead, give it a try!

Final result

Block inserter open on post edit screen by default on page load in WordPress Gutenberg



Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

Powered by WordPress