Last active
August 9, 2023 12:06
-
-
Save Web-Assembler/3d7ef50e282af72ccff8b68bb3a833e8 to your computer and use it in GitHub Desktop.
Add a custom body class based on the first Gutenberg block classes used.
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 | |
add_filter( 'body_class', 'custom_body_classes' ); | |
function custom_body_classes( $classes ) { | |
$post = get_post(); | |
if ( ! is_null( $post ) ) { | |
if ( has_blocks( $post->post_content ) ) { | |
$blocks = parse_blocks( $post->post_content ); | |
$first_block_attrs = $blocks[0]['attrs']; | |
$custom_classes = array(); | |
if ( array_key_exists( 'name', $first_block_attrs ) ) { | |
// Force the default block backgroundColour to ensure the classname is set properly. | |
if ( 'namespace/full-height-header' === $first_block_attrs['name'] && false === array_key_exists( 'backgroundColor', $first_block_attrs ) ) { | |
$first_block_attrs['backgroundColor'] = 'yellow-dark'; // This default is also set in block.json. | |
} | |
} | |
// Add a class when the background color is set on the first block. | |
if ( array_key_exists( 'backgroundColor', $first_block_attrs ) ) { | |
$custom_classes[] = esc_html( 'first-block-bgcolor-' . $first_block_attrs['backgroundColor'] ); | |
} | |
if ( ! empty( $custom_classes ) ) { | |
return array_merge( $classes, $custom_classes ); | |
} | |
} | |
} | |
return $classes; | |
} | |
// Then in scss | |
$first_block_colors: ( | |
'yellow-dark' : var(--color-yellow-dark), | |
'green-dark' : var(--color-greendark), | |
.... etc | |
); | |
@each $name, $color in $first_block_colors { | |
body.first-block-bgcolor-#{$name} { | |
.header { | |
background-color: $color; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment