Created
March 13, 2021 12:55
-
-
Save florianbrinkmann/4d97c1ab7014388ec12e0d7ab94d9115 to your computer and use it in GitHub Desktop.
Add has-\d-columns class to columns blocks after 5.3 update.
This file contains 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 has-\d-columns class to columns blocks after 5.3 update. | |
* | |
* @param string $block_content The block content about to be appended. | |
* @param array $block The full block, including name and attributes. | |
* | |
* @return string | |
*/ | |
add_filter( 'render_block', function( $block_content, $block ) { | |
// Check if we have no columns block. | |
if ( $block['blockName'] !== 'core/columns' ) { | |
return $block_content; | |
} | |
// Check if the columns block already has a has-\d-columns class. | |
if ( preg_match( '/<div class="(?:.* )?(wp-block-columns (?:.*)has-\d-columns|has-\d-columns (?:.*)wp-block-columns)(?: .*)?"(?:.*)>/', $block_content ) === 1 ) { | |
return $block_content; | |
} | |
$columns_count = count( $block['innerBlocks'] ); | |
// Add the class to the markup. | |
$block_content = preg_replace( '/<div class="(.* )?wp-block-columns( .*)?"(.*)>/', sprintf( | |
'<div class="$1wp-block-columns has-%d-columns $2"$3>', | |
$columns_count | |
), $block_content ); | |
return $block_content; | |
}, 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This version is tested in WordPress 5.7 and contains some fixes (mainly to support also custom classes for the columns block):