Top-level Pages and Children Bricks Query Loop

This Pro tutorial for Bricks users can be considered Part 2 or a variation of the earlier Bricks Query Loop for Top-level Parent Pages with Children tutorial.

Given this Page structure:

The objective is to list all top-level Pages (not just parent Pages) in the outer query loop and the child Page(s) (if present) of the current Page being iterated from the outer loop in the inner query loop.

Like this:

Note: This tutorial works with any hierarchical post type, not just page.

Step 1

Let’s first define a custom function to check if the current post has children.

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

<?php 

function bl_is_post_parent(): bool {
    $children = get_pages( array( 'child_of' => get_the_ID() ) );

    return count( $children ) > 0;
}

Whitelist the bl_is_post_parent function.

Ex.:

<?php 

add_filter( 'bricks/code/echo_function_names', function() {
  return [
    'bl_is_post_parent'
  ];
} );

You should also add any other functions (native or custom) being used in your Bricks instance in addition to bl_is_post_parent. This can be checked at Bricks → Settings → Custom code by clicking the Code review button.

More info on whitelisting can be found here.

Step 2

Edit the Page where you’d like to show the top-level pages and their children with Bricks.

Section JSON is provided near the end.

Add a Section and inside its Container, a Container (UL).

Add a Block (LI) inside the Container.

Enable query loop on the Block.

Post type: Pages

Order by: Title

Order: Ascending

Posts per page: 100 (set this to a large number that typically exceeds the total number of all the matching posts of your query rather than -1)

Enable PHP query editor.

Paste:

return [
  'post_parent' => 0,
];

Add a Basic Text element inside the Block having:

{post_title:link}

Add a Container (UL) (this will be at the same level as the outer query loop block).

Apply this dynamic data condition:

{echo:bl_is_post_parent}

Add a Block (LI) inside the Container.

Enable query loop and change settings to:

Add a Basic Text element inside the Block having:

{post_title:link}

Check on the front end.

Section JSON.