Block Editor – Trigger Gutenberg save programmatically

I have loads of data as JSON that I am trying to save to a fresh install of WordPress.

I’m using puppet to log in and create each page, and wp.blocks.createBlock To create blocks programmatically.

// Input the page title

    const headingInput = document.querySelector("#post-title-0");
    headingInput.innerHTML = json.data.heading;

    var changeEvent = new Event("change", {
        bubbles: true,
        cancelable: true,
    });
    headingInput.dispatchEvent(changeEvent);


    /**
     * Next up, create each of the gutenberg blocks
     */
    json.data.blocks.forEach((block) => {
        if (
            block.className == "feature text-feature"
        ) {
            block.content.forEach((element) => {
                if (element.hasOwnProperty("gutenbergBlock")) {
                    var el = wp.element.createElement;
                    insertedBlock = wp.blocks.createBlock(
                        element.gutenbergBlock,
                        element.attributes
                    );
                    wp.data.dispatch("core/editor").insertBlocks(insertedBlock);
                }
            });
        }
    });


 // Attempt to trigger the save:
    document
        .querySelectorAll(".editor-post-publish-button")
        .forEach((button) => {
            console.log("clicking button!");
            var clickEvent = new MouseEvent("click", {
                view: window,
                bubbles: true,
                cancelable: false,
            });
            button.dispatchEvent(clickEvent);
        });

Above, I try to click the save button to save the post, however this part doesn’t work.

Is there any way to trigger the saving of the page content? Something like this: wp.blocks.save(), I’ve explored the documentation, but can’t find anything so niche.

Leave a Comment