Skip to content

Instantly share code, notes, and snippets.

@audrasjb
Last active February 5, 2021 16:59
Show Gist options
  • Save audrasjb/379fdb2f189acbb7ef77aee9f6906052 to your computer and use it in GitHub Desktop.
Save audrasjb/379fdb2f189acbb7ef77aee9f6906052 to your computer and use it in GitHub Desktop.
Extend WordPress has_block() function to also check inside Gutenberg reusable blocks
/**
* Determine whether a $post or a string contains a specific block type,
* including blocks that are included in reusable blocks.
*
* @param string $block_name Full Block type to look for.
* @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object. Defaults to global $post.
* @return bool Whether the post content contains the specified block.
*/
function has_block_including_reusables( $block_name, $post = false ) {
if ( ! has_blocks( $post ) ) {
return false;
}
$post = ( ! $post ) ? get_the_ID() : $post;
if ( $post ) {
// This is for regular blocks
if ( has_block( $block_name, $post ) ) {
return true;
}
// This is for reusable blocks
if ( has_block( 'block', $post ) ) {
$content = get_post_field( 'post_content', $post );
$blocks = parse_blocks( $content );
if ( ! is_array( $blocks ) || empty( $blocks ) ) {
return false;
}
if ( false === strpos( $block_name, '/' ) ) {
$block_name = 'core/' . $block_name;
}
foreach ( $blocks as $block ) {
if ( $block['blockName'] === 'core/block' && ! empty( $block['attrs']['ref'] ) ) {
if ( has_block( $block_name, $block['attrs']['ref'] ) ) {
return true;
}
}
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment