Last active
February 25, 2024 00:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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