Created
September 5, 2023 20:13
-
-
Save otakupahp/a1a7021bc145893be0f4c8cb26391679 to your computer and use it in GitHub Desktop.
Add a body class if the content has a cover with an specific class
This file contains 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
/** | |
* Check if the cover block has the hero class and set a global variable. | |
* | |
* @param string $content The block content about to be rendered. | |
* | |
* @return string | |
*/ | |
function otk_cover_block( string $content ): string { | |
// The hero is the first block in the content, so we set it once. | |
global $otk_cover_block_has_hero_class; | |
if ( is_null( $otk_cover_block_has_hero_class ) ) { | |
$otk_cover_block_has_hero_class = (bool) preg_match( '/class="(.*?)wp-block-cover(.*?)hero(.*?)"/', $content ); | |
} | |
return $content; | |
} | |
add_filter( 'render_block_core/cover', 'otk_cover_block' ); | |
/** | |
* Add the hero class to the body if the cover block has the hero class. | |
* | |
* @param array $classes The body classes. | |
* | |
* @return array | |
*/ | |
function otk_body_class( array $classes ): array { | |
global $otk_cover_block_has_hero_class; | |
if ( $otk_cover_block_has_hero_class ) { | |
$classes[] = 'has-hero-cover'; | |
} | |
return $classes; | |
} | |
add_filter( 'body_class', 'otk_body_class' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment