I want to load the Gutenberg block content of one post into a custom template.
I have tried two ways.
Firstly by rendering the post content:
$args = array(
'post_type' => 'page',
'id' => $post_id
);
$your_query = new WP_Query( $args );
while ( $your_query->have_posts() ) : $your_query->the_post();
the_content();
endwhile;
I also tried rendering each block individually
$post = get_post($post_id);
$blocks = parse_blocks($post->post_content);
foreach ($blocks as $block) {
echo render_block($block);
}
In both cases it rendered the Gutenberg content, but not the related styles.
In the original page, there are both the gutenberg blocks and gutenberg inline style. Is there a way to render the blocks and the blocks styles in aother page
Use do_blocks() so the blocks render method within the post content is called and the front-end styles are enqueued as needed in your custom post template, eg:
$post = get_post($post_id);
echo do_blocks($post->post_content);
To confirm if the style sheet is queued for loading, use:
global $wp_styles;
if ( $wp_styles->queue ){
// Print out a list of all the currently enqueued styles
echo '<pre>', print_r( $wp_styles->queue ), '</pre>';
}