【问题标题】:How to get related post by category in headless wordpress?(GraphQL)如何在 headless wordpress 中按类别获取相关帖子?(GraphQL)
【发布时间】:2023-02-08 01:45:17
【问题描述】:
我的问题是那个物体很深,在某个地方我犯了一个我看不到的错误。我想显示相关帖子以发布有人点击的帖子。我通过 GraphQL 通过 Wordpress 获取日期到无头 cms nextjs 页面。
在一个组件中我选择了类别
const postCategory = post.categories.edges[0].node.name
我想将此类别的帖子显示为相关帖子:
posts.
filter((cat) => { return(
cat.categories.edges.map((z) => z.node.name == postCategory)
)})
有人做过类似的项目并看到我的错误吗?
【问题讨论】:
标签:
javascript
reactjs
arrays
wordpress
【解决方案1】:
也许这样做:
const filteredPosts = [];
for (const post in posts) {
for (const edge in post.categories.edges) {
if (edge.name == postCategory) {
filteredPosts.push(post);
}
}
}
保持简单。以这种嵌套的方式使用那些现代语法只会让人感到困惑。
【解决方案2】:
你可以有这样的查询结构:
categories {
nodes {
name
posts {
nodes {
title
}
}
}
}
并像这样过滤
const postsByCategory = post.categories.nodes[0].posts.nodes.slice(0, 4);
const relatedPosts = postsByCategory.filter((relPost) => relPost.title !== post.title);
排除当前帖子后,我只想要 3 个结果。
希望这可以帮助。