Created
July 30, 2021 12:26
-
-
Save MrZyr0/57db0e5485d03f083bf754b2a87b2211 to your computer and use it in GitHub Desktop.
Prevent Gutenberg Block from deletion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const blockNameToPrevent = 'core/block'; | |
const getBlockList = () => wp.data.select( 'core/block-editor' ).getBlocks(); | |
let blockList = getBlockList(); | |
wp.data.subscribe( () => { | |
const newBlockList = getBlockList(); | |
const blockListChanged = newBlockList !== blockList; | |
if ( blockListChanged && newBlockList.length < blockList.length ) { | |
const removedBlock = blockList.filter( ( x ) => ! newBlockList.includes( x ) )[ 0 ]; | |
if ( ! removedBlock || removedBlock.name !== blockNameToPrevent ) { | |
return; | |
} | |
const removedBlockIndex = blockList.indexOf( removedBlock ); | |
warningBlock = wp.blocks.createBlock( 'core/block', { ref: removedBlock.attributes.ref } ); | |
wp.data.dispatch( 'core/block-editor' ).insertBlocks( warningBlock, removedBlockIndex ); | |
blockList = newBlockList; | |
} | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since there is no possibility to undo the last action, the trick is to look at the list of blocks and add again the block that has just been deleted.
On paper, it is simple, and it should work, but for some reason the addition does not work and does not produce any errors…