Skip to content

Instantly share code, notes, and snippets.

@bjorn2404
Last active February 25, 2024 00:19
Show Gist options
  • Save bjorn2404/9b2b98b18c2fe47570895a63c62b8a93 to your computer and use it in GitHub Desktop.
Save bjorn2404/9b2b98b18c2fe47570895a63c62b8a93 to your computer and use it in GitHub Desktop.
Search WordPress Gutenberg blocks for a specific block name in all nested innerBlocks data
<?php
/**
* Search blocks and innerBlocks for a specific type of block
*
* @param array $blocks Blocks to search through (use parse_blocks prior to passing).
* @param string $block_name The type of block to search for.
*
* @return array Matching blocks
*/
function parse_inner_blocks( $blocks, $block_name ): array {
$block_data = [];
if ( ! is_array( $blocks ) ) {
return $block_data ;
}
foreach ( $blocks as $block ) {
if ( ! empty( $block['innerBlocks'] ) && $block_name !== $block['blockName'] ) {
$inner_data = parse_inner_blocks( $block['innerBlocks'], $block_name );
$block_data = array_merge( $block_data, $inner_data );
} elseif ( $block_name === $block['blockName'] ) {
$block_data[] = $block;
}
}
return $block_data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment