{"id":16,"date":"2024-01-18T21:16:38","date_gmt":"2024-01-18T21:16:38","guid":{"rendered":"https:\/\/giacomosecchi.com\/?p=16"},"modified":"2024-01-21T12:01:27","modified_gmt":"2024-01-21T12:01:27","slug":"how-to-get-all-wordpress-posts-in-a-gutenberg-block","status":"publish","type":"post","link":"https:\/\/giacomosecchi.com\/it\/how-to-get-all-wordpress-posts-in-a-gutenberg-block\/","title":{"rendered":"How to get all WordPress posts in a Gutenberg Block"},"content":{"rendered":"
We can retrieve quite a lot of data from the bare Javascript Browser Console if you print this If you want to manage this WordPress Core Data in your block, you can use @wordpress\/core-data<\/a><\/strong> npm module. It’s helps you get and manipalte all the core data.<\/p>\n\n\n\n First you need to install the module in your project<\/p>\n\n\n\n After installation is completed you will need to import it at the beginning of your file <\/p>\n\n\n\n In the following example you will see what explained before:<\/p>\n\n\n\n Remember to pass a store name to the select function, in this case we pass the ‘core’ store as a parameter.<\/p>\n\n\n\n I want to give you another trick, with the wp.data.select('core')<\/code> you will get all the availabe methods.<\/p>\n\n\n\n
wp.data.select('core').getCurrentTheme()<\/code> 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')<\/code><\/p>\n\n\n\n
npm install @wordpress\/core-data --save<\/code><\/pre>\n\n\n\n
import { useSelect } from '@wordpress\/data';<\/code><\/p>\n\n\n
How to get all WordPress posts in a Gutenberg Block<\/h4>\n\n\n
useSelect<\/code> is a custom react hook that you can use for retrieving props from registered selectors,
useSelect<\/code> takes a function that retrieves the select object. We will use getEntityRecors<\/a> functions to get all posts<\/p>\n\n\n\n
const posts = useSelect( ( select ) => {\n\tselect( 'core' ).getEntityRecords( 'postType', 'post', {\n\t\tper_page: 100,\n\t} );\n} );<\/code><\/pre>\n\n\n\n
useSelect<\/code> hook you can also check the status of the request you have just done. You just need to use
isResolving<\/code> method<\/p>\n\n\n\n
const isResolving = useSelect( ( select ) => {\n\tselect( 'core\/data' ).isResolving( 'core', 'getEntityRecords', [\n\t\t'postType',\n\t\t'post',\n\t\t{ per_page: 100 },\n\t] );\n} );<\/code><\/pre>\n\n\n\n
Resources<\/h4>\n\n\n\n