Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@MatzeKitt 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