2

I'm using an custom theme and I would like to take the id to the values ​​of a reusable block. I have this code:

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

I see the id of all blocks but not reusable blocks. how do I access reusable block data?

1

This is the way it worked for me:

$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'];
            }
        }
    }
}

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.