Thank you very much for such an elegant solution. My specific case is: I need my gallery block to appear as separate element adjacent to .entry-content so to have a more elegant way to position it outside of the flow of elements that make the article. I either show a featured image there, or if there is a gallery I place the gallery instead.
I solved it like this:
if ( ! has_block( 'gallery' ) ) : get_template_part entry_thumbnail ... else: get_template_part entry_gallery ...
and there simply this:
$blocks = parse_blocks( get_the_content() ); foreach ( $blocks as $block ) { if ( 'core/gallery' === $block['blockName'] ) { echo do_shortcode( $block['innerHTML'] ); break; } }
And finally in entry_content template part:
$blocks = parse_blocks( get_the_content() ); $content_markup = ''; foreach ( $blocks as $block ) { if ( 'core/gallery' === $block['blockName'] ) { continue; } else { $content_markup .= render_block( $block ); } } $priority = has_filter( 'the_content', 'wpautop' ); if ( false !== $priority ) { remove_filter( 'the_content', 'wpautop', $priority ); } echo wp_kses_post( apply_filters( 'the_content', $content_markup ) ); if ( false !== $priority ) { add_filter( 'the_content', 'wpautop', $priority ); }
Result is exactly what I need, if there is a gallery, show it outside post content, and DO NOT show it also in the post content. Awsome, thank you a LOT for this.