0

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)"
        }
    },
        (...)
}
0

Add this before your $response->data[... to render changed blocks

$markup = '';
foreach ( $blocks as $block ) {
    $markup .= render_block( $block );
}
1
  • Thanks! It works :)
    – Marek
    Feb 5 '20 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.