Master Etch with tutorials, tips, and tricks.

Search

Recent articles

Meta Box Relationship Queries in Etch

  • Meta Box
  • Queries
Official documentation: Relationship Fields

The other day, I created a relationship between the article and video post types. The goal was to show related videos to articles and related articles to video posts. Unlike the related posts you normally think of, which are based on a category or a tag, these are curated content items specifically chosen to show up. The challenge was how to get the query to show the related content. Setting up the relationship in Meta Box provided some much-needed clues.

To-From is the key

When you set up a relationship in Meta Box, it is bidirectional by default, but the naming seems a little one-sided — your relationship goes from post type 1 to post type 2.

Setting up the query

Creating the query is a little quirky. To go from the articles to the videos and retrieve the related items, you select the video post type and pass the ID of the related article.

Videos from Articles

Since the Article post type is in the From position in the relationship builder, the relationship is defined as from => articleID.

$query_args = [
  'post_type' => 'videos',
  'posts_per_page' => $count ?? 4,
  'post_status' => 'publish',
  'orderby' => 'date',
  'order' => 'DESC',
  'relationship' => [
    'id' => 'articles_to_videos',
    'from' => $articleID
  ]
];

The Etch loop would look like this:

relatedVideos($articleID: this.id) as videos

Videos to Articles

Now, when you want to query articles from a video post, the relationship argument is to “To” only because the video is in the “to” position.

$query_args = [
  'post_type' => 'articles',
  'posts_per_page' => $count ?? 4,
  'post_status' => 'publish',
  'orderby' => 'date',
  'order' => 'DESC',
  'relationship' => [
    'id' => 'articles_to_videos',
    'to' => $articleID
  ]
];

The Etch loop would look like this

relatedStories($articleID: this.id) as articles

Even if the explanation doesn’t make it easier to understand, the code should make it a snap to implement.

Share Your Thoughts

Your email address will not be published. Required fields are marked *