How do I show other posts from the same category as the current post when data.isPostType?

I want to show more posts from the same category as the current post but I’m not sure how can I do this, since the data object from a post does not contain items.

Hi @brunovaz.dev

The categories that a post is assigned to can be found in state.source.post.(id).categories. This just shows the IDs of the categories that the post is assigned to. But with the ID you can then get the category info from state.source.category, crucially the link property.

Once you have the link of the category you want you can use a fetch inside a useEffect hook to get the posts in that category into the state - example here. Once in the state you can show them alongside the current post.

Hope this helps. Let us know how you get on with this.

Thanks, this was exactly what I needed.
I created a “KeepReading” component that receives the category object and the current post id.
Then, inside the component I list all the posts from the category, and filter out the current post so it doesn’t appear in the list.
For future reference, this is how I structured the component:

const KeepReading = ({ state, actions, category, currentPost }) => {
  useEffect(() => {
    actions.source.fetch(category.link);
  }, []);

  const data = state.source.get(category.link);
  const items = data.items?.filter((post) => post.id !== currentPost);

  if (items) {
    return (
      <Wrapper>
        <Title>_Keep reading</Title>
        <Grid>
          {items.map(({ type, id }) => {
            const post = state.source[type][id];
            return (
              <PostCard
                key={id}
                variation="small"
                href={post.link}
                image={getMedia(state, post.featured_media)}
                category={post.categories[0]}
                title={post.title.rendered}
                author={post.author}
              />
            )
          })}
        </Grid>
      </Wrapper>
    )
  }

  return null
};

I didn’t do anything about the pagination yet but this is working for now.

2 Likes

Hi @mburridge,
i’m using this example(https://docs.frontity.org/api-reference-1/wordpress-source#how-to-use) to fetch posts from specific category and it’s working well;
but in some pages i need to display just 3 or 4 category;
then i’m looking for a best solution to do it

Hi @eudeskouassi

Take a look at this repo which demonstrates how to fetch and display specific categories.

Hope this helps.

thanks

1 Like