Find out how you can display a combination of entries from various Custom Post Types in the query loop block with a little bit of code.
The native WordPress block that allows you to display a list of posts (query block), 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
.
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 this filter you can display the combination of entries from different Custom Post Types.
Let’s see how:
Snippet to combine entries from several Custom Post Types in the query loop block
Add a query loop block and configure the settings to your liking. The section for “Select content type” can be left 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 919 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 the 'tutorial'
, ‘ course'
and 'portfolio'
entries on the home page ( is_front_page()
) of the website.
You can modify both the Custom Post Type by the ones you are interested in (even using ‘post’ or ‘page’) and use another conditional tag (for example, is_home, is_page…).
For example, this would be the code you would use if you wanted the query modification to be shown only on the page with ID 8385:
To see this and another 919 code snippets of this website, login or subscribe here.
As you can see, 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.
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
As you can see, it is very easy to modify the query of the native WordPress query loop block to display a combination of posts from various Custom Post Types.
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. 😉