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?

up vote 2 down vote accepted

Gutenberg has a function for this: gutenberg_parse_blocks(). To see if the first block in the post is the Heading block, you'd do this:

$post = get_post(); 

if ( gutenberg_content_has_blocks( $post->post_content ) ) {
    $blocks = gutenberg_parse_blocks( $post->post_content );

    if ( $blocks[0]['blockName'] === 'core/heading' ) {

    }
}
  • Thanks! I couldn't find this function. Funnily enough my custom code does basically the same thing but with a whole lot less code! Anyhow, marked as accepted as it's the proper built-in function. – Jeffrey von Grumbkow Aug 2 at 11:36

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
}

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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