Skip to content

Instantly share code, notes, and snippets.

@melissajclark
Last active July 26, 2024 17:58
Show Gist options
  • Save melissajclark/5816ce9720c6cb818038ae1c310a5a69 to your computer and use it in GitHub Desktop.
Save melissajclark/5816ce9720c6cb818038ae1c310a5a69 to your computer and use it in GitHub Desktop.
Filter the body_class to add classes to site <body> in specific scenarios
<?php/**
* Set Header Colour on pages based on first block's colour
*
* @link https://developer.wordpress.org/reference/functions/body_class/
*/
function client_header_body_classes( $classes ) {
// page header colours
if ( is_page() && !is_page( 'Blog' ) ) {
global $post;
$client_blocks = parse_blocks( $post->post_content );
if ( !empty( $client_blocks ) ) {
$client_first_block_bg = $client_blocks[0]['attrs']['backgroundColor'] ?? null;
if ( ( isset( $client_first_block_bg ) && ! empty( $client_first_block_bg ) ) ) {
$classes[] = esc_attr( 'client-site-header-' . $client_first_block_bg );
}
}
// body class for both event post types
} elseif ( is_singular( array( 'client_weddings', 'client_corporate_event', 'post') ) ) {
$classes[] = 'single-cwce-post';
}
return $classes;
} // client_header_body_classes
add_filter( 'body_class', 'client_header_body_classes' );
@melissajclark
Copy link
Author

Update class according to the first block used on the page. Useful for changing header colour.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment