Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wordpress check if block is used first
<?php
/**
* Block helpers
* add special classes when certain blocks appear, put this in your functions.php file or include it somewhere
*/
// add block classes in body and post class
function blocks_body_class( $classes ) {
global $post;
// check if a block is first
if ( has_blocks( $post->post_content ) ) {
$blocks = parse_blocks( $post->post_content );
if ( $blocks[0]['blockName'] === 'core/image' ) {
$classes[] = 'image-first';
}
}
// check if a block is used anywhere at all
if ( has_block( 'custom/hero' ) ) {
$classes[] = 'hero';
}
return $classes;
}
add_filter( 'post_class', 'blocks_body_class' );
add_filter( 'body_class', 'blocks_body_class' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.