Skip to content

Instantly share code, notes, and snippets.

@MrZyr0
Created July 30, 2021 12:26
Show Gist options
  • Save MrZyr0/57db0e5485d03f083bf754b2a87b2211 to your computer and use it in GitHub Desktop.
Save MrZyr0/57db0e5485d03f083bf754b2a87b2211 to your computer and use it in GitHub Desktop.
Prevent Gutenberg Block from deletion
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;
}
} );
@MrZyr0
Copy link
Author

MrZyr0 commented Jul 30, 2021

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…

@film357
Copy link

film357 commented Aug 2, 2021

blockDeletionBlocker.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment