How to add lazy field in content endpoint using Gutenberg blocks

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($bloc);

$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”: 1,
(…),
“content”: {
“rendered”: “original content”,
“protected”: false,
“lazy”: {
“markup”: “original content with changed image block (wp:image block)”
}
},
(…)
}

Read more here:: How to add lazy field in content endpoint using Gutenberg blocks

Leave a Reply

Your email address will not be published. Required fields are marked *