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;
}
} );
@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