Filter posts by two different taxonomy types and values

Is it possible to return a list of all posts that contain specific taxonomy values from two different taxonomy types?

For instance, if I have two taxonomy types:

[taxonomies]
    book = "book"
    characters = "characters"

In each post, I have defined values for those taxonomies. ex:

---
title: Chapter One
characters:
    - John
    - Betty
book:
    - Book one
---

Let’s say I have multiple books, each with multiple chapters (posts). “John” appears in 4 of those books, and in several (but not all) chapters from each book.

How do I return a list of books that has John in them (without resulting in duplicate book titles)?


My ultimate goal is to create a page that lists each character, and then lists each Book those characters appear in.

The closest I’ve managed is the following, which returns all the Books associated with each character, but the results contains duplicates (if John is in 3 chapters in “Book one”, then this code will return “Book one” 3 times).

{{ $charName := "John" }}
{{ $returns := $.Site.Pages.ByDate }}
{{ $books := (where $returns ".Params.book" "!=" nil) }}
{{ range $books }}
    {{ if and (isset .Params "characters") (in .Params.characters (lower $charName)) }}
        {{ .Params.book }}
    {{ end }}
{{ end }}

Any help would be appreciated.

That would be your taxonomy terms template. You can create it at /layouts/_default/terms.html

There is an example in the docs that might be what you need:

<section>
  <ul id="all-taxonomies">
    {{ range $taxonomyname, $taxonomy := .Site.Taxonomies }}
      <li><a href="{{ "/" | relLangURL}}{{ $taxonomyname | urlize }}">{{ $taxonomyname }}</a>
        <ul>
          {{ range $key, $value := $taxonomy }}
          <li> {{ $key }} </li>
                <ul>
                {{ range $value.Pages }}
                    <li hugo-nav="{{ .RelPermalink}}"><a href="{{ .Permalink}}"> {{ .LinkTitle }} </a> </li>
                {{ end }}
                </ul>
          {{ end }}
        </ul>
      </li>
    {{ end }}
  </ul>
</section>

And you can find a detailed tutorial on how to use taxonomies here: Handling taxonomies like a boss - update

OR

try this inside your terms.html template. Your list would be rendered at /characters

<ul>
  {{ range .Data.Pages }}
    <li>
      <a href="{{ .Permalink }}">{{ .Title }}</a>
      {{ $character := .Title | urlize }}
      <ul>
        {{ range ($.Site.GetPage "taxonomyTerm" "characters" $character).Pages }}
          <li><a href="{{ .Permalink }}">{{ .Title }}</a></li>
        {{ end }}
      </ul>
    </li>
  {{ end }}
</ul>

I guess I should have mentioned that I’m trying to do this via a shortcode so I can reference it in another page that has other unrelated (to the characters) info via a post.

Still, I’ll take a look and see if I can’t make any of this work for my purposes. :slight_smile:

Thank you!