How to get related post by category in headless wordpress?(GraphQL)

Viewed 56

My problem is that object is very deep and somewhere I make a mistake that I cannot see. I want to display related post to post which someone click. I fetch date by GraphQL via Wordpress to headless cms nextjs page.

in one component I have selected categories

  const postCategory = post.categories.edges[0].node.name

and this posts with this category I want to display as related posts:

posts.
filter((cat) => { return(
            cat.categories.edges.map((z) => z.node.name == postCategory)
         
        )})

anyone make similar project and see my mistakes?

1 Answers

Perhaps do like this:

const filteredPosts = [];

for (const post in posts) {
  for (const edge in post.categories.edges) {
    if (edge.name == postCategory) {
      filteredPosts.push(post);
    }
  }
}

Keep things simple. Using those modern syntaxes in such a nested way only confuses people.

Related