Using WordPress ‘render_block()’ PHP function

The render_block() WordPress PHP function renders a single parsed block object into an HTML string.

Usage

Here’s a generic example of how to use the function:

$parsed_block = parse_blocks($content);
$html_output = render_block($parsed_block[0]);

Parameters

  • $parsed_block (array): A single parsed block object, required.

More information

See WordPress Developer Resources: render_block

Examples

Render the First Block of a Post

This example retrieves the first block of a post and renders it as an HTML string.

// Get the post content
$post = get_post();
$content = $post->post_content;

// Parse the content into blocks
$blocks = parse_blocks($content);

// Render the first block
$html_output = render_block($blocks[0]);

// Display the HTML output
echo $html_output;

Render a Custom Block

This example creates a custom block and renders it as an HTML string.

// Create a custom block
$custom_block = array(
    'blockName' => 'core/paragraph',
    'attrs' => array(),
    'innerContent' => array('Hello, World!')
);

// Render the custom block
$html_output = render_block($custom_block);

// Display the HTML output
echo $html_output;

Render All Blocks of a Specific Type

This example renders all paragraph blocks in a post’s content.

// Get the post content
$post = get_post();
$content = $post->post_content;

// Parse the content into blocks
$blocks = parse_blocks($content);

// Loop through the blocks and render paragraph blocks
foreach ($blocks as $block) {
    if ($block['blockName'] === 'core/paragraph') {
        $html_output = render_block($block);
        echo $html_output;
    }
}

Render Nested Blocks

This example renders the inner blocks of a group block.

// Get the post content
$post = get_post();
$content = $post->post_content;

// Parse the content into blocks
$blocks = parse_blocks($content);

// Loop through the blocks and render inner blocks of a group block
foreach ($blocks as $block) {
    if ($block['blockName'] === 'core/group') {
        $inner_blocks = $block['innerBlocks'];
        foreach ($inner_blocks as $inner_block) {
            $html_output = render_block($inner_block);
            echo $html_output;
        }
    }
}

Render Block with Custom Attributes

This example creates a custom paragraph block with custom attributes and renders it as an HTML string.

// Create a custom block with custom attributes
$custom_block = array(
    'blockName' => 'core/paragraph',
    'attrs' => array(
        'fontSize' => 'large',
        'style' => array(
            'color' => array(
                'text' => '#ff0000'
            )
        )
    ),
    'innerContent' => array('Hello, World!')
);

// Render the custom block
$html_output = render_block($custom_block);

// Display the HTML output
echo $html_output;