How to query multiple post types inside Gutenberg options panel?

Ok, after some research I got the result I needed:

// Fetch all posts based on the selected postType.
const postsOptions = useSelect((select) => {
    const { getEntityRecords } = select('core');
    const { isResolving } = select('core/data');

    const postTypeSlugs = [...postType].map((element) => element.value) ?? [];

    if (!postTypeSlugs.length) {
        return [
            {
                label: __('No Filter used', 'slug'),
                value: '',
            }
        ]
    }

    const postList = [];

    postTypeSlugs.forEach((postType) => {
        const args = ['postType', postType, {per_page: -1}];

        if (!isResolving('core', 'getEntityRecords', args)) {
            const result = getEntityRecords('postType', postType, {per_page: -1});

            if (result !== null) {
                postList.push(result);
            }
        }
    });

    if (typeof(postList[0]) !== 'undefined') {
        return [
            {
                label: __('No Filter used', 'slug'),
                value: '',
            },
            ...postList[0].map((item) => {
                if (isEmpty(item)) {
                    return {};
                } else {
                    return {
                        label: item.title.rendered || '',
                        value: item.id || '',
                    };
                }
            }),
        ];
    }
});

Plus a helper from here, that checks if the array is not empty

const isEmpty = a => Array.isArray(a) && a.every(isEmpty);

This seems to be working. Not pretty, but does the job (no extra api calls as far as I can see).

Leave a Comment