Find out how to prevent single or multiple category entries from being displayed in the query loop block with a little bit of code.
The native WordPress block that allows you to display a list of entries (query loop) has improved a lot in recent updates.
In fact, in this tutorial I review all the options offered in its user interface. Although there are quite a few, it does not reach the degree of customization that can be achieved by modifying the parameters of WP_Query
.
However, the WordPress 6.1 version introduces a PHP filter that allows you to interact directly with the query, so the possibilities are extended almost to infinity.
For example, with the following filter you can prevent the display of entries from a certain category (or several if you prefer).
Let’s see how:
Snippet to prevent displaying entries of a certain category in the query loop block
Add a query loop block and configure the settings to your liking. The section for “Taxonomies” you can leave as it is, since this is the part you are going to modify using the filter.
Now add the following code at 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 this code you use the query_loop_block_query_vars
filter to modify the query and set it to exclude the entries with the category IDs 10 and 15 on the front page ( is_front_page()
) of the website.
You can modify both the categories by the ones you are interested in and use another conditional tag (e.g. is_home
, is_page
…).
You can get the category ID by checking the URL when you edit the category or, if you want to make it easier for yourself, get it displayed directly in the WordPress admin area with this tutorial.
For example, this would be the code you would use if you want the query modification to be displayed only on the page with ID equal to 55:
To see this and another 1097 code snippets of this website, login or subscribe here.
You can see here that having a filter with access to the query gives you extra flexibility compared to what the user interface offers. And this is just an example of what you can achieve.
You can access any WP_Query
parameter, so the possibilities are huge.
Just 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, the backend will not reflect the changes.
Conclusions
Now you know how easy it is to modify the query of the native WordPress query loop block so that it doesn’t show the entries of a certain category (or several ones).
Any questions? Let me know 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. 😉