Skip to content

Instantly share code, notes, and snippets.

@aristath
Last active June 27, 2022 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aristath/1bec09a1f8cf8a4d0649836ba7683d96 to your computer and use it in GitHub Desktop.
Save aristath/1bec09a1f8cf8a4d0649836ba7683d96 to your computer and use it in GitHub Desktop.
<?php
add_filter(
'render_block',
function( $html ) {
static $styled_els = array();
$styles_to_add = '';
// Find elements that have inline styles.
preg_match_all( '/<[a-zA-Z0-9]+.+style=.+>/U', $html, $matches );
// Loop elements.
foreach ( $matches as $match ) {
if ( empty( $match ) ) {
continue;
}
foreach ( $match as $part ) {
// Sanity check.
if ( false !== strpos( $part, 'style=""' ) || false !== strpos( $part, "style=''" ) ) {
continue;
}
// Get the styles.
$styles = preg_match( '/style=".+"|style=\'.+\'/', $part, $style_matches );
$has_classes = false !== strpos( $part, 'class="' );
$class_names_to_add = array();
$updated_el = $part;
// Loop styles.
foreach ( $style_matches as $style_match ) {
$styles_array = explode( ';', ltrim( ltrim( rtrim( $style_match, '"\'' ), 'style=' ), '"\'' ) );
foreach ( $styles_array as $item ) {
$item = trim( $item );
// Skip complex styles.
if ( false !== strpos( $item, '(' ) || false !== strpos( $item, '#' ) || false !== strpos( $item, '=' ) ) {
continue;
}
// The classname.
$class_name_to_add = trim( str_replace( array( ':', ' ' ), array( '-', '' ), $item ) );
if ( empty( $class_name_to_add ) ) {
continue;
}
// Build the CSS for this classname.
$class_names_to_add[] = $class_name_to_add;
if ( ! in_array( $class_name_to_add, $styled_els, true ) ) {
$styled_els[] = $class_name_to_add;
$styles_to_add .= '.' . $class_name_to_add . '{' . $item . ';}';
}
// Remove inline styles.
$updated_el = str_replace( array( " $item; ", "$item; ", " $item;", $item ), '', $part );
}
}
if ( empty( $class_names_to_add ) ) {
continue;
}
// Add classnames to the element.
$updated_el = $has_classes
? str_replace(
array( 'class="', "class='" ),
array( 'class="' . implode( ' ', $class_names_to_add ) . ' ', "class='" . implode( ' ', $class_names_to_add ) . ' ' ),
$updated_el
)
: str_replace(
'style=',
'class="' . implode( ' ', $class_names_to_add ) . '" style=',
$updated_el
);
$html = str_replace( $part, $updated_el, $html );
}
}
// Append styles.
if ( ! empty( $styles_to_add ) ) {
$html .= "<style>$styles_to_add</style>";
}
return $html;
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment