Last active
August 3, 2021 15:58
-
-
Save clarklab/6afd6cae4d8e964d9ba928b42636fe46 to your computer and use it in GitHub Desktop.
Wordpress check if block is used first
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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