How to get all WordPress posts in a Gutenberg Block

We can retrieve quite a lot of data from the bare Javascript Browser Console if you print this wp.data.select('core') you will get all the availabe methods.

wp.data.select('core').getCurrentTheme() will gives you all the header informations about the current theme. If you also run this snippet you will print all the website posts in the console: wp.data.select('core').getEntityRecords( 'postType', 'post')

If you want to manage this WordPress Core Data in your block, you can use @wordpress/core-data npm module. It’s helps you get and manipalte all the core data.

First you need to install the module in your project

npm install @wordpress/core-data --save

After installation is completed you will need to import it at the beginning of your file

import { useSelect } from '@wordpress/data';

How to get all WordPress posts in a Gutenberg Block

useSelect is a custom react hook that you can use for retrieving props from registered selectors, useSelect takes a function that retrieves the select object. We will use getEntityRecors functions to get all posts

In the following example you will see what explained before:

const posts = useSelect( ( select ) => {
	select( 'core' ).getEntityRecords( 'postType', 'post', {
		per_page: 100,
	} );
} );

Remember to pass a store name to the select function, in this case we pass the ‘core’ store as a parameter.

I want to give you another trick, with the useSelect hook you can also check the status of the request you have just done. You just need to use isResolving method

const isResolving = useSelect( ( select ) => {
	select( 'core/data' ).isResolving( 'core', 'getEntityRecords', [
		'postType',
		'post',
		{ per_page: 100 },
	] );
} );

Resources


Posted

in

by

Tags: