Created
August 9, 2025 20:59
-
-
Save kasparsd/a4208c28ac896a47fb890f349eb39a50 to your computer and use it in GitHub Desktop.
Add dynamic classes like has-background to static blocks like paragraphs and headings
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( 'render_block', function( $block_content, $block ) { | |
if ( empty( $block['blockName'] ) ) { | |
return $block_content; | |
} | |
$supports = []; | |
$block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block['blockName'] ); | |
$block_style_names = wp_get_block_style_variation_name_from_class( $block['attrs']['className'] ); | |
if ( $block_style_names ) { | |
$block_style_registry = WP_Block_Styles_Registry::get_instance(); | |
foreach ( $block_style_names as $block_style_name ) { | |
$block_style = $block_style_registry->get_registered( $block['blockName'], $block_style_name ); | |
if ( ! empty( $block_style['style_data'] ) ) { | |
$style_styles = wp_style_engine_get_styles( $block_style['style_data'], array( 'convert_vars_to_classnames' => true ) ); | |
if ( ! empty( $style_styles ) ) { | |
$supports[] = [ | |
'class' => $style_styles['classnames'] ?? '', | |
]; | |
} | |
} | |
} | |
} | |
// Note that each helper already checks if $block_type->supports is supported. | |
$supports[] = wp_apply_colors_support( $block_type, $block['attrs'] ); | |
$supports[] = wp_apply_typography_support( $block_type, $block['attrs'] ); | |
$supports[] = wp_apply_alignment_support( $block_type, $block['attrs'] ); | |
$supports[] = wp_apply_border_support( $block_type, $block['attrs'] ); | |
$supports[] = wp_apply_dimensions_support( $block_type, $block['attrs'] ); | |
$supports[] = wp_apply_shadow_support( $block_type, $block['attrs'] ); | |
$supports[] = wp_apply_spacing_support( $block_type, $block['attrs'] ); | |
$supports[] = wp_apply_aria_label_support( $block_type, $block['attrs'] ); | |
$supports = array_filter( $supports ); | |
if ( ! empty( $supports ) ) { | |
$block_element = new WP_HTML_Tag_Processor( $block_content ); | |
if ( $block_element->next_tag() ) { | |
$supports_classes = array_merge( ...array_map( fn( $classes ) => explode( ' ', $classes ), wp_list_pluck( $supports, 'class' ) ) ); | |
foreach ( $supports_classes as $support_class ) { | |
$block_element->add_class( $support_class ); | |
} | |
// TODO: Add inline CSS too. | |
$block_content = $block_element->get_updated_html(); | |
} | |
} | |
return $block_content; | |
}, 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment