Skip to content

Instantly share code, notes, and snippets.

@fumikito
Last active October 22, 2021 18:09
Show Gist options
  • Save fumikito/f80da4a68ec82acc2338c69d91c212f3 to your computer and use it in GitHub Desktop.
Save fumikito/f80da4a68ec82acc2338c69d91c212f3 to your computer and use it in GitHub Desktop.
[WordPress Gutenberg] Check next block type in block editor.
const { registerBlockType, registerBlockStyle } = wp.blocks;
const { select } = wp.data;
/**
* Get next blokc from client ID.
*/
const getNextBlock = ( id ) => {
const allBlocks = select( 'core/block-editor' ).getBlocks();
let index = null;
for ( let i = 0; i < allBlocks.length; i++ ) {
if ( allBlocks[i].clientId === id ) {
index = i;
break;
}
}
if ( null === index ) {
return false;
}
return allBlocks[ index + 1 ] || false;
}
registerBlockType( 'my-blocks/block', {
// clientId is the ID of this block.
edit( { attributes, clientId, setAttributes } ) {
const nextBlock = getNextBlock( clientId );
return (
<div>
<p>This block must precedes page break.</p>
{ ( nextBlock && 'core/nextpage' === nextBlock.name ) && (
<p class="warning">Hey, put pabebreak after this!!</p>
) }
</div>
);
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment