Discover in this tutorial how to hide the content of any block on desktop devices only, using code.
Do you want to hide certain web elements on desktop devices?
In a previous tutorial I explained how to hide elements on mobile or desktop devices using CSS. The downside of this strategy is that the content loads anyway, so it’s not the best option if you want to use it with images (or other large elements).
Therefore, in today’s tutorial you are going to see how to control that the content of a block is only loaded, and therefore displayed, on mobile devices, combining the
pre_render_block filter with the
Let’s see how:
Steps to hide the contents of a block on desktop devices
1. Choose the block you want to hide
First, choose the block whose content you want to be visible only to those visiting the site from a mobile device.
If you want this to apply to more than one set of blocks you can choose the group block as the container.
2. Add a custom CSS class
Once you have created the block, go to the “Advanced” section and add
hide-on-desktop in the block’s “Additional CSS class(es)”.
3. Modifies access to block content
Add the following code at the end of functions.php or in your functionality plugin:
In this code you use the
pre_render_block filter, which allows you to access the attributes of all blocks, along with the
In it you indicate that if it is a desktop device and the block has the CSS class
hide-on-desktop, the content of the block will not be displayed.
However, keep in mind that since you are using a PHP filter you have the limitation that you will only see the result on the web frontend, in the backend the changes will not be reflected.
Now you know how to make any block visible only to users visiting the site from a mobile device.
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. 🙂