Skip to content

Instantly share code, notes, and snippets.

@melissajclark
Created November 18, 2022 17:27
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
/**
* Set Header Colour on pages based on first block's colour
*
* @link https://developer.wordpress.org/reference/functions/body_class/
*/
function cwce_header_body_classes( $classes ) {
// page header colours
if ( is_page() && !is_page( 'Blog' ) ) {
global $post;
$cwce_blocks = parse_blocks( $post->post_content );
if ( !empty( $cwce_blocks ) ) {
$cwce_first_block_bg = $cwce_blocks[0]['attrs']['backgroundColor'] ?? null;
if ( ( isset( $cwce_first_block_bg ) && ! empty( $cwce_first_block_bg ) ) ) {
$classes[] = esc_attr( 'cwce-site-header-' . $cwce_first_block_bg );
}
}
// body class for both event post types
} elseif ( is_singular( array( 'cwce_weddings', 'cwce_corporate_event', 'post') ) ) {
$classes[] = 'single-cwce-post';
}
return $classes;
} // cwce_header_body_classes
add_filter( 'body_class', 'cwce_header_body_classes' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment