Discover in this tutorial how to add a custom CSS class to the block of your choice automatically using code.
All blocks in the editor allow you to add additional CSS classes from the user interface. In fact, this is an option we have used in many tutorials, to customize layouts, modify queries or even hide blocks.
But sometimes it can be more interesting to be able to add them programmatically. In this tutorial we will see how you can do it.
Code to assign a custom CSS class to a WordPress block programmatically
Below you can see 3 snippets that you can add to the end of functions.php or in your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
In these snippets you use the render_block_{$this->name}
filter in combination with the WP_HTML_Tag_Processor
class to add the “custom-class” CSS class, but you can replace it with any class you want.
As you can see, for each example you have to customize the filter (e.g. render_block_core/group
) and the HTML tag (e.g. div
). If you want to use it for another block you just have to modify these parameters.
To get even more out of this strategy you can use it in conjunction with WordPress conditional tags.
Conclusion
Thanks to the render_block_{$this->name}
filter and the WP_HTML_Tag_Processor
class you can add custom CSS classes to the block you want automatically.
Any questions? I read you in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉