如果块嵌套(递归),如何通过块名称查找古腾堡块



我需要从 ACF 古腾堡块中获取一些数据,但它嵌套在嵌套块中,所以

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

不工作。

你需要创建一个递归函数。代码将如下所示:

<?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;
}

相关内容

  • 没有找到相关文章

最新更新