Get Gutenberg Blocks without the_content()
Asked Answered
A

2

5

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?

Awl answered 18/7, 2019 at 15:56 Comment(0)
S
6

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.

Soemba answered 18/7, 2019 at 17:46 Comment(6)
Hey Sami! Ok, I've got an array with the blocks! But is there any way to display the blocks without needing to layout the array?Awl
@LedilsonMotta Please check the code now. I have added the foreach loop and render the block in it. You can remove the print from it as well.Soemba
Almost there! Rendered most of the blocks correctly, but some blocks such as You Tube and Soundcloud, didn't rendered, just appears the url. I Think this is because we aren't using the apply_filters() that contains in the_content() tag. You already helped me a lot, I'm fine with the solutions You gave me, but if You want to solve this completely feel free!Awl
@LedilsonMotta Filters can be applied on render_block. developer.wordpress.org/reference/hooks/render_blockSoemba
Got an error. I could see that the apply_filters is inside de function render_block(), here: developer.wordpress.org/reference/functions/render_block. How can I use the apply_filters on your example above?Awl
@LedilsonMotta You need to use add_filter not apply_filtersSoemba
I
2
$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 );
Intestinal answered 24/9, 2019 at 15:49 Comment(2)
@ggorlen the code above is based on this function do_blocksIntestinal
Thank you, the comments help clarify the code, and it's not a bad idea to throw the link inside the post as an edit.Katydid

© 2022 - 2024 — McMap. All rights reserved.