getEntityRecord without knowing the post type

The question:

In Gutenberg there’s the getEntityRecord selector that allows you to get the data of a post of a specific post type:

// get the post object of a page with post id = 42
const post = useSelect( ( select ) =>
    select('core').getEntityRecord( 'postType', 'page', 42 )
);

My question is, is there a similar selector for when you don’t know the post type of a post beforehand? I have a meta field that stores an array of post ids of different post types and right now I’m unable to get the full post objects.

Any ideas?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

My question is, is there a similar selector for when you don’t know the post type of a post beforehand?

No, at the current time of writing there is not.

The fundamental problem is that the REST API doesn’t provide a generic mechanism for getting a post type given a post ID. You can retrieve a post and it will say post but to do this you need to know the type in advance to hit the correct URL.

Since the entity Record API relies on these endpoints, there technically are no post IDs. There’s a page record with an ID, or a post record with an ID, etc

So if you want to do this properly, you need to either save the post type, restrict the types allowed for that meta field, or loop through the different entity types to see which ones return a 404 and which one doesn’t.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment