简体   繁体   中英

How to find a gutenberg block by blockName if blocks are nested (recursively)

I need to get some data from an ACF Gutenberg block, but it is nested in a nested block, so

<?php
$blocks = parse_blocks( $pid->post_content );
foreach ( $blocks as $block ) {
    if ( $block['blockName'] === 'acf/your-block-name' ) {
        //do something
    }
}

is not working.

You need to create a recursive function. The code will look like:

<?php
$blocks = parse_blocks($pid->post_content);
foreach ($blocks as $block) {
    $myAcfBlock = getMyAcfBlock($block);
    if($myAcfBlock){
        //do something
    }
}

function getMyAcfBlock($blockObject)
{
    if ($blockObject['blockName'] === 'acf/your-block-name') {
        return $blockObject;
    }
    if (!empty($blockObject['innerBlocks'])) {
        foreach ($blockObject['innerBlocks'] as $innerBlock) {
            $innerBlockObject = getLandigFormBlock($innerBlock);
            if ($innerBlockObject) {
                return $innerBlockObject;
            }
        }
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM