In the Gutenberg context, getEntityRecords is used to retrieve a collection of entities, usually returned as an array.
If we look into the entities.js file, we can see an array of entities that we can request. We won’t go through each of them, but rather we will see how to use it.
Entities can have a “kind”. For example, the post
and page
entities are of the postType
kind. If there are additional custom post types registered, those will be of the postType
kind as well.
Basic usage
For the entities which have a kind, we request as follows:
// This will return all the posts under the 'page' post type.
getEntityRecords( 'postType', 'page' );
Code language: JavaScript (javascript)
However, there are entities which don’t have a kind, such as user
or media
. To request these, we use root
as the kind.
// Returns all the users.
getEntityRecords( 'root', 'user' );
// Returns all the media.
getEntityRecords( 'root', 'media' );
Code language: JavaScript (javascript)
Passing arguments to the request
Entities are related to the WP REST API.
Suppose we want to query a post which has the word “keyboard” in its post title. This is how we can do it:
const query = {
search: 'keyboard',
};
getEntityRecords( 'postType', 'page', query );
Code language: JavaScript (javascript)
Comparing this to the /wp/v2/posts
endpoint, scroll down to the arguments section under List Posts. All the arguments listed can be used in our query.
As you might have already guessed it, if you want to query a post with the following parameters:
- The word “Gutenberg” in the title.
- has author with the ID: 1
- is tagged under Tags with IDs 17, 18
Inside a component or a plugin, it would be as follows:
import { useSelect } from "@wordpress/data";
function MyComponent() {
const { filteredPosts } = useSelect( ( select ) => {
const { getEntityRecords } = select( 'core' );
// Query parameters.
const query = {
author: 1,
search: "Gutenberg",
tags: [17, 19]
};
return {
filteredPosts: getEntityRecords( 'postType', 'post', query ),
}
} );
/* For the sake of example, we are just logging instead
* of returning anything from the Component.
*/
console.log( filteredPosts );
return false;
}
Code language: JavaScript (javascript)
Leave a Reply