I'm trying to inject some data into blocks via PHP but am running into trouble with parse_blocks/serialize_blocks breaking my content
I'm using the default 2020 theme and have no plugins installed
add_action('wp', function() {
$oPost = get_post(119);
printf("<h1>Post Content</h1><p>%s</p>", var_dump($oPost->post_content));
$aBlocks = parse_blocks($oPost->post_content);
printf("<h1>Parsed Blocks</h1><pre>%s</pre>", print_r($aBlocks, true));
$sSerialisedBlocks = serialize_blocks($aBlocks);
printf("<h1>Serialised Blocks</h1><p>%s</p>", var_dump($sSerialisedBlocks));
}, PHP_INT_MAX);
The first print (just outputting the post content) contains this text...
<h3>What types of accommodation are available in xxxx?<\/h3>
The second (after parsing into blocks) contains this...
<h3>What types of accommodation are available in xxxx?</h3>
But after re-serialising the blocks I get this...
\u003ch3\u003eWhat types of accommodation are available in xxxx?\u003c\/h3\u003e
Could someone tell me what I'm doing wrong?
EDIT
Ok so I followed the source code for serialize_blocks and it does seem like this is intentional with serialize_block_attributes explicitly converting some characters
My question is why then are these characters showing up in the WYSIWYG instead of being correctly converted back?
save
method of a block is for. Have you confirmed the block editor is unable to handle the reserialized data?<
and>
is used. btw if you're doing this because you want to modify the HTML markup in PHP of blocks rendered with javascript, then no, just no. You can't do that. Your blocks will show as invalid when you reopen the block editor and fail validation. However if you do not care about that, then I do not see the problem. Just JSON decode the result to decode the characters.