首页 > 解决方案 > 古腾堡自定义阻止 php 渲染问题

问题描述

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

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

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

},

通过此回调调用渲染函数:

register_block_type( 'my-plugin/latest-post', array(
    'render_callback' => 'my_plugin_render_block_latest_post',
) );

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

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

我的问题是:我怎样才能只为自定义块禁用它?我可以使用这个:

remove_filter( 'the_content', 'wpautop' );

但我不想改变默认行为。

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

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

标签: wordpresswordpress-gutenberggutenberg-blocks

解决方案


我们默认有:

add_filter( 'the_content', 'do_blocks', 9 );
add_filter( 'the_content', 'wpautop' );
add_filter( 'the_excerpt', 'wpautop' );
...

我浏览了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;

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


推荐阅读