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?

2 Answers2

5

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.

Sami Ahmed Siddiqui
  • 2,328
  • 1
  • 16
  • 29
  • 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? – Ledilson Motta Jul 18 '19 at 18:29
  • @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. – Sami Ahmed Siddiqui Jul 19 '19 at 06:00
  • 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! – Ledilson Motta Jul 19 '19 at 13:39
  • @LedilsonMotta Filters can be applied on `render_block`. https://developer.wordpress.org/reference/hooks/render_block/ – Sami Ahmed Siddiqui Jul 19 '19 at 17:58
  • Got an error. I could see that the **apply_filters** is inside de function **render_block()**, here: https://developer.wordpress.org/reference/functions/render_block. How can I use the **apply_filters** on your example above? – Ledilson Motta Jul 19 '19 at 19:26
  • @LedilsonMotta You need to use `add_filter` not `apply_filters` – Sami Ahmed Siddiqui Jul 19 '19 at 19:41
1
$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 );
  • @ggorlen the code above is based on this function [do_blocks](https://developer.wordpress.org/reference/functions/do_blocks) – samuelpodina Sep 26 '19 at 09:07
  • 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. – ggorlen Sep 26 '19 at 15:04