Now that you’ve defined parent / child relationship, you’re probably looking for a way to display those children. I’ll show you how to do it using a View.
Let’s use our house / rooms example. When we display a house, we’d like to show its rooms.
We have two cases to consider:
- When displaying a single house, display its rooms.
- When listing houses, display rooms for each house.
In the first case, when we display a single house, we’ll need to display child posts (rooms) of the current page (house). In the second case, when we display a list of houses, we’ll display child posts of the parent set by the View.
Create a View and choose to load the child items. In our case, Rooms.
Then, add a filter. Choose ‘Post relationship – post is child of’:
To use this View in a single House page, you should choose Post where this View is shown. It means that you’ll get Rooms that belong to the displayed House.
And, if this View goes inside another View which lists Houses, you should choose ‘Post set by parent View‘. Then, you’ll get the Rooms of the House in the external View. Once you’ve created this View for rooms, you can insert it into the Houses View. The most convenient way to do this is to use a Content Template for each House and include the Rooms View inside it.
There are other options in that filter. Post with ID set by a shortcode attribute or Post with ID set by an URL parameter will let you reuse the same View but filtering by different post relationships. Take a look at the documentation about passing arguments to Views. You can also get posts that are children of a specific fixed given Post.
Now, we’re practically done. This View will load the Rooms that we need and all that’s left to do is to actually display them.
Head down to the Loop Output section. You can use the Loop Wizard to help you to display the data for each Room. You can see the details about how it works in the Loop Wizard documentation. Also, you might want to read some extra documentation about the Views Output Loop.
And, this is how it looks once you are done:
When we view a House, we can see all its rooms.