Check what Gutenberg blocks are in post_content

I’m working on a design that has different styling if a certain Gutenberg block is present on a page. In other words, if the first block is a custom built Gutenberg block, the post_title is rendered elsewhere due to design choices made.

Is there any function in WordPress to get a list of all Gutenberg blocks present in the post_content?

3

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' ) {
    }
}

Leave a Comment