Skip to content

Instantly share code, notes, and snippets.

@florianbrinkmann
Created March 13, 2021 12:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save florianbrinkmann/4d97c1ab7014388ec12e0d7ab94d9115 to your computer and use it in GitHub Desktop.
Save florianbrinkmann/4d97c1ab7014388ec12e0d7ab94d9115 to your computer and use it in GitHub Desktop.
Add has-\d-columns class to columns blocks after 5.3 update.
<?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 );
@MatzeKitt
Copy link

MatzeKitt commented Mar 15, 2021

This version is tested in WordPress 5.7 and contains some fixes (mainly to support also custom classes for the columns block):

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