Get Posts for a certain category

Hi

I wanted to re-implemented the /news/-page on one of my frontity pages. So that’s why I created a handler and wanted to retrieve the news category at first (two later on query all the posts of that category):

export default {
 priority: 10,
   pattern: "/news1/",
   func: async ({ route, params, state, libraries }) => {
     const response = await libraries.source.api.get({
       endpoint: "/wp/v2/categories/",
       params: {
         per_page: 100 // To make sure you get all of them
       }
     });

     const items = response.json();
     console.log(items)
     const currentPageData = state.source.data[route];
     Object.assign(currentPageData, {
       items
     });
   },
 }

But I am not gettting any results, from the API. Anyone got an idea what I am doing wrong?

Hi @phn

response.json() returns a promise, so you need to await it:

const items = await response.json();
2 Likes

aaaah, thanks a lot :slight_smile:

I managed to get it working like his:

export default {
    priority: 10,
    pattern: "/news1/",
    func: async ({ route, params, state, libraries }) => {
        const categoryResponse = await libraries.source.api.get({
            endpoint: "/wp/v2/categories/",
            params: {
                slug: "news"
            }
        });

        state.source.data["/news1/"].isNewsList = true;
        const categories = await categoryResponse.json();
        const postsResponse = await libraries.source.api.get({
            endpoint: "/wp/v2/posts/",
            params: {
                categories: categories[0].id
            }
        });

        const posts = await postsResponse.json();
        const currentPageData = state.source.data[route];
        Object.assign(currentPageData, {
                posts
            });
        },
    }

Now, I have the problem that during the custom post listing I don’t have the attachments loaded, so I cannot display the featured_media. Any suggestions on how to fetch the attachments?

Hi @phn

Could you provide a link to a repo so that I can take a look at your code. Thanks.

Yes, for sure. Here you go:

Hi @mburridge or anyone else on here has any idea on that issue?