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 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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