Related Posts Grouped by Custom Field Value when using ACF Relationships in Bricks

In the Bricks Facebook group a user asks:

Let's summarize the situation.

  • Location CPT (view in question)
    • Related Boat field (Relationship)
  • Boat CPT
    • Related Location field (Relationship)
    • Cabin field (Select)
  • Relationship

with the CPTs and field groups created using ACF.

Requirement: On single locations, show related boats grouped by cabin field.

Rough outline of what we should do:

  • Get array of boat IDs related to the current location
  • Loop through the above boat IDs, get the Cabin field value for each and construct an associative array of cabins => boat IDs.
  • Outer query loop: Custom cabins query type
    • Inner query loop: boats where post__in => bl_get_boats_by_cabin( 'outer cabin' )

Sample data (numbers in brackets are post IDs):

  • Location 1 (199): Boat 1 (202), Boat 3 (204), Boat 4 (205)
  • Location 2: Boat 2 (203), Boat 3 (204)
  • Location 3: Boat 4 (205)
  • Boat 1 (202): V-berth (cabin)
  • Boat 2 (203): Saloon (cabin)
  • Boat 3 (204): Saloon (cabin)
  • Boat 4 (205): V-berth (cabin)

This Pro tutorial shows how related posts of a different CPT can be grouped by post meta when viewing single posts of a CPT in Bricks.

Step 1

Create location and boat CPTs.

Location Fields:

Boat Fields:

Step 2

Edit your Location CPT and Boat CPT entries and populate the custom fields for each.

Step 3

Let's create a custom function that loops through the boats related to the current location and returns an associative array having the value of cabin field as the array keys and an array of related boat post objects as the array values.

Ex.: For 'Location 1' post:

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

(code snippet title suggestion: Get cabins => boat IDs for current location)

This is a BricksLabs Pro tutorial.

For full access login below or create your BricksLabs Pro account

Instant access to 390+ Bricks code tutorials with BricksLabs Pro