I'm creating some custom dynamic blocks for WordPress Gutenberg editor (following this link ).
I use the PHP render for these blocks, meaning I have this code on save:
save: function( props ) {
// Rendering in PHP
return;
},
The render function is called via this callback:
register_block_type( 'my-plugin/latest-post', array(
'render_callback' => 'my_plugin_render_block_latest_post',
) );
I'm not gonna post the function code since is irrelevant in this case. (I do a WP_Query and display some custom post data and return a html code),
My problem is that WP Gutenberg takes the output from the function and adds
<p> and <br>
tags (classic wpautop behaviour).
My question is: How can I disable that only for custom blocks? I could use this:
remove_filter( 'the_content', 'wpautop' );
but I don't want to alter the default behaviour.
Some additional findings. The php function use for block rendering use get_the_excerpt(). Once this function is used (and i assume is happening for get_the_content() ) the wpautop filter is applied and the html markup of the block gets messed up.
I don't know if this is a bug or the expected behavior but is there any simple solution to this that does not involve removing the filter ? ( For ex on themeforest removing this filter is not allowed.)
We have by default:
add_filter( 'the_content', 'do_blocks', 9 );
add_filter( 'the_content', 'wpautop' );
add_filter( 'the_excerpt', 'wpautop' );
...
I skimmed through the do_blocks()
(src) and if I understand correctly it removes the wpautop
filtering if the content contains any blocks, but restores the filter for any subsequent the_content()
usage.
I wonder if your render block callback contains any such subsequent usage, as you mentioned a WP_Query
loop.
One could e.g. try:
$block_content = '';
remove_filter( 'the_content', 'wpautop' ); // Remove the filter on the content.
remove_filter( 'the_excerpt', 'wpautop' ); // Remove the filter on the excerpt.
... code in callback ...
add_filter( 'the_content', 'wpautop' ); // Restore the filter on the content.
add_filter( 'the_excerpt', 'wpautop' ); // Restore the filter on the excerpt.
return $block_content;
within your my_plugin_render_block_latest_post()
callback code.