Skip to content

Instantly share code, notes, and snippets.

@vyskoczilova
Last active June 18, 2025 07:28
Show Gist options
  • Save vyskoczilova/f9f07c75ae239cfe17cd17f46bfff835 to your computer and use it in GitHub Desktop.
Save vyskoczilova/f9f07c75ae239cfe17cd17f46bfff835 to your computer and use it in GitHub Desktop.
WP block editor tweaks
<?php
/**
* Skip rendering of empty paragraph, heading, group, and columns blocks.
*
* - Paragraphs/headings: skipped if they contain only whitespace or &nbsp;
* - Group/columns: skipped if all inner blocks are empty or filtered out
*
* @param string $block_content The rendered HTML content.
* @param array $block The parsed block array.
* @return string|void Filtered content or null to skip rendering.
*/
function skip_empty_blocks($block_content, $block) {
$block_name = $block['blockName'];
// Return early for non-targeted blocks
if (!in_array($block_name, ['core/paragraph', 'core/heading', 'core/group', 'core/columns'], true)) {
return $block_content;
}
// Paragraph and heading: remove if only whitespace or &nbsp;
if ($block_name === 'core/paragraph' || $block_name === 'core/heading') {
if (preg_match('/^<(?P<tag>p|h[1-6])[^>]*>(?:\s|&nbsp;)*<\/\1>$/i', trim($block_content))) {
return;
}
return $block_content;
}
// Group and columns: skip if no inner blocks or no visible content
if ($block_name === 'core/group' || $block_name === 'core/columns') {
if (empty($block['innerBlocks'])) {
return;
}
// If content is empty, assume all inner blocks were also skipped
if (trim($block_content) === '') {
return;
}
}
return $block_content;
}
add_filter('render_block', 'skip_empty_blocks', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment