Skip to content

Instantly share code, notes, and snippets.

@clarklab
Last active August 3, 2021 15:58
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save clarklab/6afd6cae4d8e964d9ba928b42636fe46 to your computer and use it in GitHub Desktop.
Save clarklab/6afd6cae4d8e964d9ba928b42636fe46 to your computer and use it in GitHub Desktop.
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