Discover in this tutorial how to use the same archive template to display different Custom Post Types (CPT), in a WordPress theme.
The archive template is in charge of displaying the list of posts.
It is very common for a block theme to include the archive.html
template, which is in charge of its design. And this template usually uses the query loop block, in which you have to choose the type of entry you want to be displayed, for example, posts.
This has the limitation that, if you have several types of CPTs (podcast, masterclass, tutorials…) you have to duplicate the template and rename it(archive-podcast.html
…).
But if you have many Custom Post Types, which you want to display with the same layout on the archive page, you can use some code to avoid duplicating the template.
Let’s see how:
Steps to use the same archive template for different CPTs
1. Create the archive.html template layout
Go to the “Site Editor” and choose the archive.html
template (if it doesn’t exist you can create it), add the query loop block, and create the layout you want.
If you have doubts, in this tutorial I explain in depth how the block works and its possibilities.
2. Add the logic that allows you to filter the content
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.
This code uses the query_loop_block_query_vars
filter along with the is_post_type_archive
conditional to indicate which Custom Post Type entries will be loaded in each case.
With the above example you indicate that, if the archive page is podcast, the query loop block should filter only entries of this CPT. But you can extend the conditional to include all the CPTs you need.
This strategy can save you a lot of time on a website with many CPTs, allowing the changes you make to a single file to be displayed on all archive pages.
Conclusion
If you have an installation with many CPTs and don’t want to create a file template for each of them, you now know how to achieve this with a little bit of code.
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. 😉