To check if a block is the first child in the Gutenberg editor, you can use JavaScript and the wp.data
API provided by WordPress. Here’s a code snippet that shows how to do this:
- First, make sure you’ve enqueued your JavaScript file in your theme or plugin with the necessary dependencies:
function my_enqueue_scripts() {
wp_enqueue_script(
'my-script-handle',
get_template_directory_uri() . '/js/my-script.js',
array( 'wp-blocks', 'wp-dom-ready', 'wp-data' ),
'1.0.0',
true
);
}
add_action( 'enqueue_block_editor_assets', 'my_enqueue_scripts' );
Replace the path to the JavaScript file according to your theme or plugin structure.
- Next, create the
my-script.js
file and add the following code to check if the block is the first child:
(function (wp) {
var domReady = wp.domReady;
var select = wp.data.select;
var subscribe = wp.data.subscribe;
domReady(function () {
var unlisten = subscribe(function () {
var selectedBlock = select('core/block-editor').getSelectedBlock();
if (selectedBlock) {
var clientId = selectedBlock.clientId;
var parentClientId = select('core/block-editor').getBlockRootClientId(clientId);
var firstChildClientId = select('core/block-editor').getFirstMultiSelectedBlockClientId();
if (parentClientId) {
var parentBlock = select('core/block-editor').getBlock(parentClientId);
var isFirstChild = parentBlock.innerBlocks[0].clientId === clientId;
console.log('Is this the first child block?', isFirstChild);
}
unlisten();
}
});
});
})(window.wp);
This code listens for block selection and checks if the selected block is the first child of its parent. It will log the result in the browser console.
Keep in mind that this code works for the current Gutenberg editor.
There is chance that something have changed since last time I checked so please refer to the official documentation for the latest information:
Block Editor Handbook: https://developer.www.ads-software.com/block-editor/
wp.data
API: https://developer.www.ads-software.com/block-editor/reference-guides/packages/packages-data/