Ledilson Motta
Ledilson Motta

Reputation: 63

Get Gutenberg Blocks without the_content()

I'm trying to display the gutenberg blocks from a specific post ID inside another one.

The question is, does exist a function that I can get all blocks from one post and display it anywhere in the site? Just like get_the_content do?

Upvotes: 5

Views: 5364

Answers (2)

samuelpodina
samuelpodina

Reputation: 21

$post_id = 1; // ID of the post
// parse_blocks parses blocks out of
// a content string into an array
$blocks = parse_blocks( get_the_content( $post_id ) );
$content_markup = '';
foreach ( $blocks as $block ) {
    // render_block renders a single block into a HTML string
    $content_markup .= render_block( $block );
}
// this will apply the_content filters for shortcodes
// and embeds to contiune working
echo apply_filters( 'the_content', $content_markup );

Upvotes: 2

Sami Ahmed Siddiqui
Sami Ahmed Siddiqui

Reputation: 2386

I think you may get the Blocks of the Gutenberg using this way.

$post_id = 1;
$post = get_post( $post_id ); 

if ( has_blocks( $post->post_content ) ) {
    $blocks = parse_blocks( $post->post_content );
    print'<pre>';print_r($blocks);print'</pre>';
    foreach( $blocks as $block ) {
        echo render_block( $block );
    }
}

Note: I haven't tested the code by myself.

Upvotes: 6

Related Questions