WordPress的Gutenberg可复用块

时间:2019-10-28 作者:Simon

我使用的是自定义主题,我想将id带到值​​可重用块的。我有以下代码:

<?php
$post = get_post();
if ( has_blocks( $post->post_content ) ) {
   $blocks = parse_blocks( get_the_content() ); 
     foreach($blocks as $block) {
        $id= isset($block[\'attrs\'][\'id\']) ? $block[\'attrs\'][\'id\'] : \'\';
        echo $id;
     }
}
我看到了所有块的id,但没有可重用块。如何访问可重用块数据?

1 个回复
SO网友:maysi

这就是我的工作方式:

$post = get_post( $post_id );

if ( has_blocks( $post->post_content ) ) {
    $blocks = parse_blocks( $post->post_content );

    foreach ( $blocks as $block ) {
        if ( isset( $block[\'attrs\'][\'id\'] ) ) {
                echo $block[\'attrs\'][\'id\'];
        } elseif ( \'core/block\' === $block[\'blockName\'] ) {
            $block_content = parse_blocks( get_post( $block[\'attrs\'][\'ref\'] )->post_content );
            if ( isset( $block_content[0][\'attrs\'][\'id\'] ) ) {
                echo $block_content[0][\'attrs\'][\'id\'];
            }
        }
    }
}

相关推荐