Wordpress - Check what Gutenberg blocks are in post_content
WordPress 5.0+ has a function for this: parse_blocks()
. To see if the first block in the post is the Heading block, you'd do this:
$post = get_post();
if ( has_blocks( $post->post_content ) ) {
$blocks = parse_blocks( $post->post_content );
if ( $blocks[0]['blockName'] === 'core/heading' ) {
}
}
The solution I'm using as of writing check the post_content for the Gutenberg HTML comments. Due to future Gutenberg changes this might not work in the future.
<?php
$post_content = get_the_content( get_the_ID() ); // Get the post_content
preg_match_all('<!-- /wp:(.*?) -->', $post_content, $blocks); // Get all matches in between <!-- /wp: --> strings
// $blocks[1] contains the names of all the blocks present in the post_content
if ( in_array( 'heading', $blocks[1] ) ) {
// Post content contains a wp:heading block
}
else {
// Post content does not contain a wp:heading block
}