Using WordPress ‘get_the_block_template_html()’ PHP function

The get_the_block_template_html() WordPress PHP function returns the markup for the current block template.

Usage

echo get_the_block_template_html();

Parameters

  • None

More information

See WordPress Developer Resources: get_the_block_template_html()

Examples

Display Block Template HTML

This example will display the block template HTML for the current template.

// Display the block template HTML
echo get_the_block_template_html();

Add Custom Wrapper to Block Template HTML

This example adds a custom wrapper div around the block template HTML.

// Get the block template HTML
$block_template_html = get_the_block_template_html();

// Add custom wrapper
echo '<div class="custom-wrapper">' . $block_template_html . '</div>';

Modify Block Template HTML with DOM Manipulation

This example manipulates the block template HTML using PHP’s DOMDocument.

// Get the block template HTML
$block_template_html = get_the_block_template_html();

// Create a new DOMDocument instance
$dom = new DOMDocument();
@$dom->loadHTML($block_template_html);

// Modify the DOM as needed
// ...

// Save and display the modified HTML
echo $dom->saveHTML();

Filter Block Template HTML using a WordPress Filter

This example uses a WordPress filter to modify the block template HTML.

function modify_block_template_html($block_template_html) {
    // Modify the block template HTML as needed
    // ...

    return $block_template_html;
}
add_filter('block_template_html', 'modify_block_template_html');

// Display the modified block template HTML
echo get_the_block_template_html();

Cache Block Template HTML using Transients API

This example caches the block template HTML using the Transients API for better performance.

// Attempt to get the cached block template HTML
$cached_block_template_html = get_transient('cached_block_template_html');

if (false === $cached_block_template_html) {
    // If not cached, get the block template HTML and cache it
    $block_template_html = get_the_block_template_html();
    set_transient('cached_block_template_html', $block_template_html, HOUR_IN_SECONDS);
} else {
    // If cached, use the cached block template HTML
    $block_template_html = $cached_block_template_html;
}

// Display the block template HTML
echo $block_template_html;