Skip to content

Instantly share code, notes, and snippets.

@awps
Created December 10, 2021 10:50
Show Gist options
  • Save awps/b9eb865aeda503d9f52a70d924435f04 to your computer and use it in GitHub Desktop.
Save awps/b9eb865aeda503d9f52a70d924435f04 to your computer and use it in GitHub Desktop.
How to modify the Gutenberg blocks from post content with PHP
<?php
namespace ZeroWP;
class PostBlocks
{
/**
* @param \WP_Post|int $post
* @param callable $callback
*
* @return string
*/
public static function getNewContent($post, $callback)
{
$post = get_post($post);
$content = $post->post_content;
if (has_blocks($post->post_content)) {
$blocks = parse_blocks($post->post_content);
$parsedBlocks = self::parseBlocks($blocks, $callback);
$content = serialize_blocks($parsedBlocks);
}
return $content;
}
/**
* @param \WP_Block_Parser_Block[] $blocks
* @param callable $callback
*
* @return \WP_Block_Parser_Block[]
*/
protected static function parseBlocks($blocks, $callback): array
{
$allBlocks = [];
foreach ($blocks as $block) {
// Go into inner blocks and run this method recursively
if ( ! empty($block['innerBlocks'])) {
$block['innerBlocks'] = self::parseBlocks($block['innerBlocks']);
}
// Make sure that is a valid block (some block names may be NULL)
if ( ! empty($block['blockName'])) {
$allBlocks[] = $callback($block); // the magic is here...
continue;
}
// Continuously create back the blocks array.
$allBlocks[] = $block;
}
return $allBlocks;
}
}
@awps
Copy link
Author

awps commented Dec 10, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment