Tailoring the Gutenberg editor’s blocks to meet your website’s specific needs is now more straightforward with WordPress’s HTML API. The following PHP code snippet demonstrates how to add custom classes and attributes to the content of native Gutenberg paragraph, list, and image blocks.
The Code
<?php
// Add custom classes to Gutenberg paragraph blocks
add_filter('render_block_core/paragraph', function ($block_content) {
$p = new WP_HTML_Tag_Processor($block_content);
if ($p->next_tag()) {
$p->add_class('wp-block-paragraph');
if ($p->next_tag('a')) {
$p->add_class('wp-block-paragraph__link');
}
}
return $p->get_updated_html();
});
// Add custom classes to Gutenberg list blocks
add_filter('render_block_core/list', function ($block_content) {
$list = new WP_HTML_Tag_Processor($block_content);
if ($list->next_tag()) {
$list->add_class('wp-block-list');
}
return $list->get_updated_html();
});
// Add lazy loading attribute to Gutenberg image blocks
add_filter('render_block_core/image', function ($block_content) {
$picture = new WP_HTML_Tag_Processor($block_content);
if ($picture->next_tag('img')) {
$picture->set_attribute('loading', 'lazy');
}
return $picture->get_updated_html();
});
How It Enhances Your Blocks
- Paragraph Blocks: Adds a
wp-block-paragraphclass to each paragraph and awp-block-paragraph__linkclass to links within paragraphs for more targeted styling. - List Blocks: Appends a
wp-block-listclass to each list, allowing for consistent list styling across your site. - Image Blocks: Sets the
loadingattribute tolazyon images for improved page load performance by deferring the loading of off-screen images.
Benefits for Your WordPress Site
- Custom Styling: With added classes, you can create specific styles for different block types, enhancing the visual appeal of your content.
- Performance Optimization: Lazy loading images can significantly reduce initial page load time, save bandwidth, and improve the overall user experience.
- Scalable Customizations: As your site grows, these enhancements ensure that your content remains consistent and performs well.
By incorporating this code into your WordPress site, you can take advantage of the HTML API to customize Gutenberg blocks easily, making your content stand out and your site run smoothly.

Leave a Reply