Last active
June 18, 2025 07:28
-
-
Save vyskoczilova/f9f07c75ae239cfe17cd17f46bfff835 to your computer and use it in GitHub Desktop.
WP block editor tweaks
This file contains hidden or 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 | |
/** | |
* Skip rendering of empty paragraph, heading, group, and columns blocks. | |
* | |
* - Paragraphs/headings: skipped if they contain only whitespace or | |
* - 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 | |
if ($block_name === 'core/paragraph' || $block_name === 'core/heading') { | |
if (preg_match('/^<(?P<tag>p|h[1-6])[^>]*>(?:\s| )*<\/\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