How can I filter nested query loops (2 taxonomies)?

Hello all,

I have a custom post type (Activity) with two taxonomies (Book & Activity Category), and I would like to display them in sub groups: Main groups by the 1st taxonomy, and sub-groups by the 2nd taxonomy. Is this possible?

Right now I almost have it working, but the posts are only filtered by the second taxonomy, not by the first.

I have 3 query loops:

  1. On the container: Type – Term; Taxonomy – Book (Activity)
  2. On the content: Type – Term; Taxonomy – Activity Categories (Activity)
  3. On the post list: Type – Post; Post type – Activity; with a Taxonomy Query: Taxonomy – Activity Category (Activity); Terms – {term id}

How can I filter the post list by the first taxonomy as well? Is this possible in Bricks? Thanks for any help.

3 Likes

Yes, it is with some custom code as there is no {parent_id} variable in Bricks. Just needed it myself and here it is. However, it outputs headings even if there are no child elements. Which is a pity for me, maybe someone finds the solution to even get this right.

I have some custom PHP that does it right, but it has no styling and is not the solution expected.

Assignment
Activity is a CPT activity
Book is taxonomy book
Activity category is a taxonomy activity_category

You want to show
Book > Activity category > List all Activity posts

Instruction
Place this into a code block Inside the Book taxonomy loop. It temporarily stores the term_id of the parent (Book) taxonomy in a global variable.

<?php
  $GLOBALS['parent_term_id'] = {term_id};
?>

Use this Bricks Query editor (PHP) for the inner Activity loop to solely show posts having both taxonomies:

$parent_term_id = $GLOBALS['parent_term_id'];

$query = [
    'post_type' => 'activity',
    'tax_query' => [
        'relation' => 'AND',
        [
            'taxonomy' => 'book',
            'field' => 'term_id',
            'terms' => $parent_term_id,
        ],
        [
            'taxonomy' => 'activity_category',
            'field' => 'term_id',
            'terms' => {term_id},
        ],
    ],
];
return $query;

Hint:
You could use the Bricks query loop UI as well e.g. by implementing a function that returns the parent_id and adding {echo:get_parent_term_id} in the terms.

Place this into functions.php

<?php
function get_parent_term_id() {
  if (isset($GLOBALS['parent_term_id'])) {
    return esc_html($GLOBALS['parent_term_id']);
  }
}
?>

However, it didn’t work immediately and stopped with the PHP query.

@Matej Could this be natively integrated? E.g. as {parent_term_id} for the parent loop, or {term_id_1} for first loop term_id, term_id_2 for second loop and so on.