Skip to content

Instantly share code, notes, and snippets.

@misfist
Created July 26, 2021 20:13
Show Gist options
  • Save misfist/17813e4218b0d310848f5c941b88f8dc to your computer and use it in GitHub Desktop.
Save misfist/17813e4218b0d310848f5c941b88f8dc to your computer and use it in GitHub Desktop.
Check if post contains a specific reusable block
function has_reusable_block( $block_name, $id = false ) {
$id = (!$id) ? get_the_ID() : $id;
if( $id ) {
if ( has_block( 'block', $id ) ) {
// Check reusable blocks
$content = get_post_field( 'post_content', $id );
$blocks = parse_blocks( $content );
if ( ! is_array( $blocks ) || empty( $blocks ) ) {
return false;
}
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