Discover how to sort entries by modification date in the query block with a little bit of code.
The native WordPress block that allows you to display a list of posts, the query block, has improved a lot in the latest 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 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 have the entries displayed by modification date, instead of publication date.
This can be practical if you want to keep the publication date, but have the entry you updated to appear earlier in the list.
Let’s see how:
Snippet to sort posts by update date in WordPress query loop block
Add a query loop block and configure the settings to your liking. The “Sort by” section you can leave it as is, since this is the part you are going to modify using the filter.
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 filter query_loop_block_query_vars
to modify the query and ask it to sort the entries by modification date on the main page ( is_front_page()
) of the website.
You can modify both the categories by others that interest you and the conditional tag (for example, 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 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 424:
To see this and another 1097 code snippets of this website, login or subscribe here.
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 parameter of WP_Query
, so the possibilities are tremendous.
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 can see how easy it is to modify the query of the native WordPress query loop block to sort the entries by modification date, instead of by publication date.
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. 😉