Discover in this tutorial how to hide the content of any block only on mobile devices, using code.
Do you want to hide certain web elements on mobile devices?
In a previous tutorial I explained how to hide elements on mobile devices using CSS. The downside of this strategy is that the content loads anyway, so it’s not the most recommended 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 desktop, combining the
pre_render_block filter with the
Let’s see how:
Steps to hide the content of a block on mobile devices
1. Choose the block you want to hide
First, choose the block whose content you want to be visible only when visiting the site from a desktop device.
If you want this to apply to multiple 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-mobile in the block’s “Additional CSS class(es)”.
3. Modify 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 all blocks attributes, along with the
In it you indicate that, if it is a mobile device and the block has the CSS class
hide-on-mobile, the content of the block will not be shown.
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 desktop device.
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. 😉