Working with relational fields inside query loops

Learn how to use relational fields in Bricks loop

The relational fields can be used in the Brick builder query loops.

Unidirectional relations

First of all, you need to enable code execution in Bricks.

Now, suppose you want to loop the posts belonging to a certain Movie in a unidirectional relation.

Inside the Movie single or archive template you need to set a query loop using a custom PHP code:

The code will be something like this:

// The relational field. Follow this syntax: {cf_box_field}
$postIds = '{cf_m_rel}'; 
$postIds = explode(",", $postIds);

return [
  'post_type' => 'post', // or change if it is not the right post type
  'posts_per_page' => -1, // to display all the posts
  'post__in' => $postIds,
];

The variable $postIds represents the post IDs to be queried in the loop.

Bidirectional relations

Let's see an example.

First of all, suppose you have a CPT called movie and another one called post.

Setup a one-one bidirectional relation between.

You'll have something like this:

Now, move to Bricks editor.

To fetch all the posts from the above relational field value, you need to set a query loop adding a custom meta query:

  • meta keys: the name of the movie meta field

  • value: {post_id}

  • operator: LIKE

In this case, only one post will be fetched, since the relational is one-one.

Last updated