Discover in this tutorial how to use conditional load for a stylesheet only when a certain block is loaded in the frontend.
Instructions to load a stylesheet conditionally, associated to the loading of a block
Add the following snippet to the functions.php file:
To see this and another 1091 code snippets of this website, login or subscribe here.
In the first part of the code you register the stylesheet or script using the wp_register_style
function.
In the second, you use the render_block
filter in conjunction with the enqueue_block_style
function to indicate that when a given block is present the stylesheet is loaded.
In this case, the stylesheet is only loaded when the core/loginout
block is present, but the idea is that you change it to whatever block you are interested in.
You could also use the render_block_{$this->name}
filter, in this case it would be render_block_core/loginout
.
Conclusions
A good practice that every developer should apply is to use conditional loading, whenever possible. In this tutorial you have learned how to use conditional load for a stylesheet only if a block is present in the frontend.
If you have any question, please leave it in the comments. And if you want to give me a suggestion for future snippets, please send it through the contact form.
Benefits of being a subscriber. 🙂