Created
December 10, 2021 10:50
-
-
Save awps/b9eb865aeda503d9f52a70d924435f04 to your computer and use it in GitHub Desktop.
How to modify the Gutenberg blocks from post content with PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Details and usage example: https://zerowp.com/how-to-modify-the-gutenberg-blocks-from-post-content-with-php/