1

I'm facing difficulties in determining the ideal timing to programmatically change settings that are provided by the theme in the themes block editor. My goal is to modify these settings as soon as they are fully loaded into the block editor.

To achieve this, I have implemented the following approach, aiming to change the settings as late as possible:

async function blockEditorSubHandler() {
    console.log("callback fired")
    if (!select(blockEditor).getBlocks().length) return

    if (!wp.data.select("core/block-editor").getSettings().allowedBlockTypes.includes("foo")) {
        await dispatch(blockEditor).updateSettings({ allowedBlockTypes: ["foo"] })
        console.log("passed")
    }
}
subscribe(blockEditorSubHandler, "core/block-editor")

The issue I'm facing is that the code passes through the if statements four times before the callback stops being invoked by state changes triggered during the loading process. At this stage, when I check wp.data.select('core/block-editor').getSettings().allowedBlockTypes in the console, it correctly shows that ["foo"] is set. However, this indicates that the block settings were loaded right before the final callback invocation.

How do I determine precisely when it is the right time to change the settings so that the changes are available to the user ASAP?

bewww
  • 39
  • 2
  • 6

1 Answers1

0

I would use the block_editor_settings_all filter in PHP to ensure the settings sent to the Editor are loaded immediately, rather than JavaScript in this scenario. As PHP parses the settings for the theme, using the PHP filter avoids the async loading issue of JavaScript, eg:

PHP

function so_76324559_allow_foo( $editor_settings, $editor_context ){
    // Possibly do some checks here rather than replacing allowedBlockTypes
    // unless "foo" is the only block allowed
    $editor_settings['allowedBlockTypes'] = ['foo'];
    
    return $editor_settings;
}

add_filter( 'block_editor_settings_all', 'so_76324559_allow_foo', 10, 2 );

The result of running wp.data.select('core/block-editor').getSettings().allowedBlockTypes in the browser console immediately shows "foo" as enabled.

S.Walsh
  • 3,105
  • 1
  • 12
  • 23