Halloween Sale 15% off Ends in See the plans
PHP

Body Classes for the Blocks Used on a Page

Adds body classes such as "has-block-cover" or "has-block-gallery" for the main blocks a post or page contains, so CSS can adapt the header or layout to the content.

Don’t have WPIDE yet? Install it on your site

Code

// Blocks to look for.
$wpide_body_class_blocks = array( 'core/cover', 'core/gallery', 'core/table', 'core/video', 'core/embed', 'core/query' );

add_filter( 'body_class', function ( $classes ) use ( $wpide_body_class_blocks ) {
    if ( ! is_singular() ) {
        return $classes;
    }

    $post = get_queried_object();

    if ( ! $post instanceof WP_Post || ! has_blocks( $post ) ) {
        return $classes;
    }

    foreach ( $wpide_body_class_blocks as $block ) {
        if ( has_block( $block, $post ) ) {
            $name      = 0 === strpos( $block, 'core/' ) ? substr( $block, 5 ) : str_replace( '/', '-', $block );
            $classes[] = 'has-block-' . sanitize_html_class( $name );
        }
    }

    return $classes;
} );

Notes

Only the blocks in the list are checked, which keeps it fast. Add any block name you want to style against.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.