Most WordPress blocks output some sort of HTML markup to the page when rendered on the front end.
Luckily, that to the excellent extensibility features of WordPress, all blocks markup when rendered is run through a filter. This allows developers like you and make to make changes to the block output.
To do this you hook a function into the render_block
filter, or you can use the render_block_{block_name}
specific filters to targeting specific blocks.
For example, to target the core paragraph block you would hook into the render_block_core/paragraph
filter hook.
Here is an example:
<?php
/**
* Modify the core paragraph block.
*
* @param string $block_content The block content about to be rendered.
* @param array $block The full block including name and attributes.
* @param array $instance The block instance (unique ID).
*
* @return string The maybe modified block content.
*/
function hd_modify_core_paragraph_block( $block_content, $block, $instance ) {
// you can check for this here such as block attributes.
// if the block has an additional class of 'my_classname' then do something.
if ( 'my_classname' === $block['className'] ) {
// wrap the block in a div for example.
$block_content = '<div class="my-classname">' . $block_content . '</div>';
}
// return the block content.
return $block_content;
}
add_filter( 'render_block_core/paragraph', 'hd_modify_core_paragraph_block', 10, 3 );