通过PHP解析嵌套块(在列中等)

时间:2021-05-04 作者:jshwlkr

我正在检查一个自定义块的帖子,并试图通过PHP在网站的其他地方呈现这些块的内容。我的方法如下:

      if ( has_block( \'custom/block\' ) ) {
        global $post;

        $blocks = parse_blocks( $post->post_content );
        foreach ( $blocks as $block ) {
          if ( \'custom/block\' === $block[\'blockName\'] ) {
              echo "<div>";
              echo apply_filters( \'the_content\', render_block( $block ) );
              echo "</div>";
              break;
          } 
      }

因此,我基本上会检查帖子中的特定块,当我找到它时,我会输出它的内容,然后打破循环,因为我只关心第一个块。问题是,当您将“自定义/块”放在列块(或任何类似的块)中时,此循环将丢失它。我不知道如何有效地研究块的内部块来解决这个问题,除了像这样迭代所有可能的父块并检查它们的胆量:

      if ( has_block( \'custom/block\' ) ) {
        global $post;

        $blocks = parse_blocks( $post->post_content );
        foreach ( $blocks as $block ) {
          if ( \'custom/block\' === $block[\'blockName\'] ) {
              echo "<div>";
              echo apply_filters( \'the_content\', render_block( $block ) );
              echo "</div>";
              break;
          } elseif ( \'core/columns\' === $block[\'blockName\'] ) {
            $column = apply_filters( \'the_content\', render_block( $block ) );
            // mess around with the $column here to get the appropriate equivalent output
          }
          // elseif iterate through other potential parent blocks
      }

有什么建议可以让这变得不那么混乱吗?

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

如果我理解正确,您可以使用递归函数来循环内部块以查找特定块。示例:

/* Sample usage, assuming $post is defined properly:

    $blocks = parse_blocks( $post->post_content );
    wpse_387661( $blocks );
*/
function wpse_387661( $blocks ) {
    foreach ( $blocks as $block ) {
        if ( ! empty( $block[\'innerBlocks\'] ) ) {
             wpse_387661( $block[\'innerBlocks\'] );
        } elseif ( \'custom/block\' === $block[\'blockName\'] ) {
            echo apply_filters( \'the_content\', render_block( $block ) );
            break; // this could mean that inner blocks were never looped
        }
    }
}