getEntityRecord without knowing the post type

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x