How to access InnerBlocks Attributes within the Parent Block on the WordPress Gutenberg Editor

Developing custom blocks in WordPress Gutenberg editor can be a challenging but rewarding experience. As developers, we often need advanced access to InnerBlocks for advanced block development. In this tutorial, I will discuss how to get access to InnerBlocks attributes within the parent block.

Accessing InnerBlocks on JavaScript Edit Component

Accessing all InnerBlocks within the block Edit component is quite easy. By using the @wordpress/data module, you can access them by using the following code:

const { __ } = wp.i18n;
const { useSelect } = wp.data;
const { store: blockEditorStore } = wp.blockEditor;
/**
* Block Edit Component
*/
const Edit = (props) => {
const { clientId } = props;
const innerBlocks = useSelect(
(select) => select(blockEditorStore).getBlock(clientId).innerBlocks,
);
console.log( innerBlocks ); // This will log all the inner blocks on your browser console
};
view raw edit.js hosted with ❤ by GitHub

Accessing InnerBlocks on PHP Block Render Function

The WP_Block class can be accessed during the PHP block render, which gives you wide control and access over the block output. Below is an example of how you can easily access inner block attributes on the parent block render function.

<?php
/**
* Render Custom Block
*
* @param array $atts Block Attributes
* @param string $content Block Content (InnerBlocks)
* @param WP_Block $block_class Block Class Instance
* @return string Block Markup
*/
function render( $atts, $content, $block_class ) {
// Check how many inner blocks are available
$item_count = $block_class->inner_blocks->count();
if ( $item_count < 1 ) {
return '';
}
ob_start();
?>
<div>
<?php
// iterate over the available inner blocks
for ( $index = 1; $index <= $item_count; $index++ ) :
// Get the inner block data
$inner_block = $block_class->inner_blocks->current();
// Holds the inner block attribute
$attribute = $inner_block->attributes;
// This will display the attributes data
var_dump( $attribute );
// increase the index in the WP_Block_List class used to retrieve the current block
$block_class->inner_blocks->next();
endfor;
// reset the index in the WP_Block_List class to the initial state
$block_class->inner_blocks->rewind();
?>
</div>
<?php
return ob_get_clean();
}
?>
view raw render.php hosted with ❤ by GitHub

Conclusion

In this tutorial, I have discussed how to get advanced access to InnerBlocks within the parent block in WordPress Gutenberg editor. With these techniques, you can create more advanced custom blocks with ease. I hope you found this tutorial helpful and informative. If you have any questions or suggestions, please feel free to leave a comment below.

Leave a Reply

I won’t send you spam. Unsubscribe at any time.

%d bloggers like this: