Check if Gutenberg Blocks are being used in Post or Page

During development of a site for a client, they requested the site to be built using Gutenberg blocks. On import of other existing posts from a previous site (that wasn’t using blocks), we found that content was simply put into the page on import. This was fine, except the blocks we designed were fullwidth with an inner container. With the imported post content, this resulted in the content spanning the full width of the page, edge to edge.

So I needed a snippet of code to check if the content is using blocks. If not, then add some HTML to wrap in a container. Here’s how:

<?php
$post = get_post(); // get the current post
if ( !has_blocks( $post->post_content ) ) { // check if using blocks, if not...
?>
<div class="container">
<?php the_content(); ?>
</div>
<?php } else { // otherwise, output the block content without container ?>
<?php the_content(); ?>
<?php } ?>

Useful post? Share it

Leave a Reply

Your email address will not be published. Required fields are marked *