Skip to content

Instantly share code, notes, and snippets.

@lunule
Created September 6, 2023 22:01
Show Gist options
  • Select an option

  • Save lunule/d0d6fcc65d4b84f500f4dd1cb60da3b5 to your computer and use it in GitHub Desktop.

Select an option

Save lunule/d0d6fcc65d4b84f500f4dd1cb60da3b5 to your computer and use it in GitHub Desktop.
[WP Core - Extended has_block checker with support to reusable blocks] #gutenberg #wp #wordpress #core #has_block #block #blocks #conditionals #checker #check
<?php
/**
* Determines whether a $post or a string contains a specific block type,
* including blocks that are included in reusable blocks.
*
* @author Jb Audras – @audrasjb on socials.
*
* @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.
*
* @here https://jeanbaptisteaudras.com/2021/09/how-to-extend-has_block-function-to-also-check-for-gutenberg-reusable-blocks/
*/
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