Filter content by field from two different post types

Hi!

How do I filter content by the same field from two different post types?

So I have two pages (post types) with different content. The first one is episodes and the other is blog posts. In both I have a field called “Theme”. I want to create a template file that shows all posts with a given theme value from both episode and blog post. So the visitor should be able to click on a theme value and the all episodes and blog posts with that theme.

The theme value should also be in the URL. I don’t use the panel, only FTP.

It’s probably easy but I can’t get it to work with my knowledge.

My website is: https://bibelpodden.se

Translation from Swedish to English if it helps:
Alla avsnitt = All Episodes (<- in the burger menu)
Bloggen = The Blog (<- in the burger menu)
Tema = Theme (<- in the post meta on every episode and blog post)

Thank you very much in advance!

Well, you are already filtering, so basically all that needs to be done is merge both collections in your new template:

<?php
$posts = page('blog')->children()->visible();
$episodes = page('episode')->children()->visible();
$allTypes = new Pages(array($posts, $episodes));
if($tema = param('tema')) {
  $allTypes = $allTypes->filterBy('tema', $tema);
}

Note that your filtering links have to link to this page. I don’t know if you want to have a list of links at the top of that page? Or do you want the current tags to link to this page?

Thank you very much @texnixe! Some minor changes to your code and solved.

For someone seeing this there is an parenthesis missing after if($tema = param('tema'). It should be if($tema = param('tema'))

Shame on me, I corrected it above. Not sure if new glasses or a bigger screen or maybe better a combination of both would actually help. Or more sleep… :sleeping:

1 Like