Removing selected Gutenberg block from post content in WordPress

There are cases where you want to hide a Gutenberg block from readers. To do it you should add new filter for the_content.

August 24, 2023 wordpressphpgutenberg

Removing a custom block from content

1
<?php
2
add_filter('the_content', 'remove_to_do_from_content', 5);
3
4
function remove_to_do_from_content($content){
5
if (has_block('custom/todo') === false) {
6
return $content;
7
}
8
9
$parsed = parse_blocks($content);
10
foreach ($parsed as $index => $block) {
11
if ($block['blockName'] === 'custom/todo') {
12
unset($parsed[$index]);
13
}
14
}
15
16
return serialize_blocks($parsed);
17
}

Take a look at the third argument. Our filter has to be run before the build-in converter (Gutenberg -> HTML) so we have to set a priority to 5.

We do not have break after first found because we can have more than one todo block

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Leave a comment