How to find the first Gutenberg block used on a post in WordPress
Here’s a handy function to check if a Gutenberg block is the first block used on a post or page.
<?php
/**
* Check if the first block matches the passed in block className.
*
* @param array $block_class_names The unique className block attribute.
* @param WP_Post $post The WordPress post.
* @return bool
*/
function weba_is_first_block( $block_class_names, $post = null ) {
// Use the provided $post object or fall back to the global post.
$post = ( $post ) ? $post : get_post();
if ( is_null( $post ) ) {
return false;
}
if ( has_blocks( $post->post_content ) ) {
$blocks = parse_blocks( $post->post_content );
$first_block_attrs = $blocks[0]['attrs'];
// Check if the first block exists and has the required blockName.
if ( ! empty( $first_block_attrs ) && isset( $first_block_attrs['name'] ) ) {
if ( in_array( $first_block_attrs['name'], $block_class_names, true ) ) {
return true;
}
}
}
return false;
}You can use this like this:
<?php
if ( ! weba_is_first_block( array( 'namespace/my-block-name' ) ) ) {
echo 'Custom header';
}In the first function argument, you can pass one or more block names in an array which is useful if you want to check multiple blocks at once and return true if any of them are present. E.g.
<?php
$blocks_to_check = array(
'namespace/block-one',
'namespace/block-two',
'core/cover',
);
if ( weba_is_first_block( $blocks_to_check ) ) {
// Do something.
}