The parse_blocks() WordPress PHP function parses blocks out of a content string.
Usage
$blocks = parse_blocks($content);
Parameters
$content (string)– Required. The post content to parse.
More information
See WordPress Developer Resources: parse_blocks()
Examples
Display First YouTube Block in a Post
This example shows how to display the first YouTube block found in a post.
function display_first_youtube_block() {
global $post;
$blocks = parse_blocks($post->post_content);
foreach ($blocks as $block) {
if ('core-embed/youtube' === $block['blockName']) {
echo apply_filters('the_content', render_block($block));
break;
}
}
}
Check if Post has a Specific Block
This example checks if a post has a specific block, such as the core/paragraph block.
function has_specific_block($block_name) {
global $post;
$blocks = parse_blocks($post->post_content);
foreach ($blocks as $block) {
if ($block_name === $block['blockName']) {
return true;
}
}
return false;
}
Count the Number of Blocks in a Post
This example counts the number of blocks in a post.
function count_blocks() {
global $post;
$blocks = parse_blocks($post->post_content);
return count($blocks);
}
Get the First Block of a Specific Type
This example retrieves the first block of a specific type, like the core/image block.
function get_first_block_of_type($block_name) {
global $post;
$blocks = parse_blocks($post->post_content);
foreach ($blocks as $block) {
if ($block_name === $block['blockName']) {
return $block;
}
}
return null;
}
Extract All Blocks of a Specific Type
This example extracts all blocks of a specific type, like the core/quote block.
function get_all_blocks_of_type($block_name) {
global $post;
$blocks = parse_blocks($post->post_content);
$filtered_blocks = array();
foreach ($blocks as $block) {
if ($block_name === $block['blockName']) {
$filtered_blocks[] = $block;
}
}
return $filtered_blocks;
}