如何使用Gutenberg块在内容终结点中添加惰性字段

时间:2020-02-05 作者:Marek

I\'m trying to add a "lazy" field to the "content" endpoint using "rest_prepare_post".

I do this by adding "rest_prepare_post" filter. Then I check if "$post->post_content" has gutenberg blocks. After that I search in the loop all those that have blockName set as "core/image". Then I edit the contents of this block.

My problem is to put a changed HTML into "content" field, which will be a copy of "content[rendered]". Below I insert the code.

<?php
class EndpointLazyLoading
{
    public function __construct()
    {
        add_filter( \'rest_prepare_post\', [ $this, \'add_content_lazy_field\' ], 1, 3);
    }

    public function add_content_lazy_field($response, $post, $request)
    {
        if (has_blocks($post->post_content)) {
            $blocks = parse_blocks($post->post_content);

            foreach ($blocks as &$block) {
                if (isset($block[\'blockName\']) && $block[\'blockName\'] === \'core/image\') {
                    // some magic with $block[\'innerContent\'][0] and $block[\'innerHTML\']
                }
            }
            unset($block);

            $response->data[\'content\'][\'lazy\'] = [
                \'markup\'  => post_password_required($post) 
                    ? \'\' 
                    : \'^^^^^^^^content that i try to add^^^^^^^^\',
                \'protected\' => (bool) $post->post_password
            ];
        }
    }
}

I want to see something like this:

GET domain.com/blog/wp-json/wp/v2/posts/6222?_lazy
{
    "id": 6222,
        (...),
    "content": {
        "rendered": "original content",
        "protected": false,
        "lazy": {
            "markup": "original content with changed image block (wp:image block)"
        }
    },
        (...)
}
1 个回复
最合适的回答,由SO网友:Vitauts Stočka 整理而成

将此添加到$response->data[... 渲染更改的块

$markup = \'\';
foreach ( $blocks as $block ) {
    $markup .= render_block( $block );
}

相关推荐

为内置钩子调用do_action和Apply_Filters是否安全?

我正在开发一个插件,它需要复制一些内置的WordPress逻辑。(此逻辑不能用任何内置方法调用,也不能独立连接到。)在这个动作序列中,WordPress的正常行为是调用动作挂钩(do_action(\'wp_login\', ...)) 和过滤器挂钩(apply_filters(\'login_redirect\', ...)).如果在对应于在Core中调用它们的时间点调用它们,那么直接从我的插件调用这些内置钩子是否安全(并且是可以接受的做法)?或者,其他与此相关的开发人员期望在非常特定的时间执行操作的风