古腾堡自定义块 php 渲染问题

Cre*_*rem 2 wordpress wordpress-gutenberg gutenberg-blocks

我正在为 WordPress Gutenberg 编辑器创建一些自定义动态块(按照此链接)。

我对这些块使用 PHP 渲染,这意味着我保存了以下代码:

save: function( props ) {
    // Rendering in PHP
      return;

},
Run Code Online (Sandbox Code Playgroud)

渲染函数是通过这个回调调用的:

register_block_type( 'my-plugin/latest-post', array(
    'render_callback' => 'my_plugin_render_block_latest_post',
) );
Run Code Online (Sandbox Code Playgroud)

我不会发布功能代码,因为在这种情况下无关紧要。(我做了一个 WP_Query 并显示一些自定义帖子数据并返回一个 html 代码),

我的问题是 WP Gutenberg 从函数中获取输出并添加 <p> and <br>标签(经典的 wpautop 行为)。

我的问题是:如何仅对自定义块禁用它?我可以用这个:

remove_filter( 'the_content', 'wpautop' );
Run Code Online (Sandbox Code Playgroud)

但我不想改变默认行为。

一些额外的发现。用于块渲染的 php 函数使用 get_the_excerpt()。一旦使用了这个函数(我假设 get_the_content() 正在发生),wpautop 过滤器就会被应用,块的 html 标记就会被弄乱。

我不知道这是一个错误还是预期的行为,但是有没有不涉及删除过滤器的简单解决方案?(对于主题森林的 ex 不允许删除此过滤器。)

bir*_*ire 5

我们默认有:

add_filter( 'the_content', 'do_blocks', 9 );
add_filter( 'the_content', 'wpautop' );
add_filter( 'the_excerpt', 'wpautop' );
...
Run Code Online (Sandbox Code Playgroud)

我浏览了do_blocks()( src ),如果我理解正确,它会wpautop在内容包含任何块时删除过滤,但会恢复过滤以供后续the_content()使用。

我想知道您的渲染块回调是否包含任何此类后续用法,如您提到的WP_Query循环。

例如,可以尝试:

$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;
Run Code Online (Sandbox Code Playgroud)

在您的my_plugin_render_block_latest_post()回调代码中。