Discover how you can display a selection of posts in custom order with the native WordPress query loop block and a little bit of code.
The native WordPress block that allows you to display a list of posts, now called Query Loop, is becoming more and more versatile.
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 we can reach by modifying the WP_Query
class parameters.
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 get the entries to be displayed in a custom order of your choice.
This can be handy if you want to have full control over the order in which the elements are displayed. For example, on the OsomPress plugin page we use this strategy.
Let’s see how:
Snippet to customize the order of posts in the native WordPress query loop block
Add a query loop block and configure the settings to your liking. The “Sort by” section you can leave as it is, as this is the part you are going to modify using the filter.
Add the following code snippet to your functionality plugin:
To see this and another 1091 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 order the entries according to your interest on the page with ID=73 ( is_page(73)
) of the website.
You can get the ID of the posts by checking the URL when you edit the post or, if you want to make it easier for yourself, get it displayed directly in the WordPress admin with this tutorial.
Once you have defined the order of the entries, you use the orderby
parameter to order them as you want.
Keep in mind that since you are using a PHP filter, you have the limitation that you will only see the result in the web frontend, in the backend the changes will not be reflected.
Conclusions
You can see how easy it is to modify the native WordPress query loop block to order the post as you prefer.
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. 😉