32

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?

1
  • 1
    There is a website whichblocks.com When you type a web page url, it scans the page and find out which gutenberg blocks is used in the page.
    – Teena Babu
    Feb 14, 2020 at 9:33

3 Answers 3

45

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

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
}
0

As of the release of 5.0 these functions have been deprecated with Gutenberg now integrated into the core. I imagine, but have not confirmed that these functions still exist in the Gutenberg standalone plugin.

Instead of gutenberg_content_has_blocks use has_blocks

Instead of gutenberg_parse_blocks use parse_blocks

1
  • 2
    @JeffreyvonGrumbkow thing is, ian-hoyte has to low rep to edit or comment =)
    – honk31
    Mar 4, 2019 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.