Discover how to sort or display posts depending on a custom field 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 the last 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, WordPress 6.1 version introduced 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 use a custom field to display or not some entries.
Let’s see how:
Snippet to modify the query loop block query based on a custom field
Add a content listing block and configure the settings to your liking.
Then, 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 ask it to display only posts that have a read time of less than 5 minutes.
In this case, it takes the custom field data created by the EditorsKit plugin, but you can use any custom field.
Another option is to display only the entries that have a certain custom field present. For that, this would be the code you would use:
To see this and another 1097 code snippets of this website, login or subscribe here.
You would only have to replace _your_metakey
with the key of the custom field you are interested in.
You can see that having a filter with access to the query gives you extra flexibility 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 tremendous.
However, keep in mind that since you are using a PHP filter you will only see the result in the web frontend, in the backend the changes will not be reflected.
Conclusions
Now you know how easy it is to modify the query of the native WordPress query loop block to display or sort the entries based on a custom field.
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. 🙂