Site icon Hip-Hop Website Design and Development

How to query multiple post types inside Gutenberg options panel?

I’m using React select so that I can create a block option that will give me the option of selecting post types and posts based on the selected post types. Basically, a query block that is in the works in Gutenberg plugin if I’m not mistaken.

Now the thing that’s bothering me the most is the fact that I cannot find out the best way to fetch all the posts from the selected options.

For instance I can fetch all the allowed post types like this:

    const postTypeOptions = useSelect((select) => {
        const { getPostTypes } = select('core');

        const items = getPostTypes() ?? [];

        const data = items.filter((element) => manifest.allowed.postTypes.find((item) => element.slug === item)) ?? [];

        return data.map((item) => {
            return {
                label: item.labels.name,
                value: item.slug,
                taxonomies: item.taxonomies,
            };
        }) ?? [];
    });

I’m inside the options part for my block, and I have a manifest.json, where I can filter allowed post types (I don’t need all the post types available for me).

What the above code will do is, when I select my block, it will do an API fetch to get all the post types using getPostTypes(), which is in my case equivalent of wp.data.select('core').getPostTypes().

Now, fetching things like posts can be done using getEntityRecords() like

wp.data.select( 'core' ).getEntityRecords( 'postType', 'post' )

Which will give me posts in my WP. I can replace the post for any custom post type to fetch that custom post type posts.

But the problem is I cannot get all the posts from multiple post types.

The reason is that underneath this, the getEntityRecords is pinging the API endpoint, and there is no way to retrieve all the posts from one endpoint from multiple post types in one go.

So how do I solve this? Create a custom endpoint that will return all the posts based on what I pass as arguments of the endpoint? Doing fetch in the useSelect is not great, as that will trigger every time I touch the block. Using stuff from wp.data.select uses caching and React store to avoid that I guess.

Any pointers into how to achieve that would be super helpful.