In addition to loading the wp-api script as mentioned here:
wp_enqueue_script( 'wp-api' ); // or use below when enqueueing as dependency
//wp_enqueue_script( 'my_script', 'path/to/my/script', array( 'wp-api' ) );
You should also know that each collection is a function (equivalent to a class in PHP), so you need to use the new keyword to instantiate a collection. Example:
var postsCollection = new wp.api.collections.Posts();
postsCollection.fetch( {
data: { per_page: 2 }
} ).done( function( posts ){
console.log( 'Title of the first item is: ' + posts[0].title.rendered );
} );
However, with Gutenberg, you’d likely want to or you can use the api-fetch/wp.apiFetch package:
-
Enqueue the
wp-api-fetchscript:wp_enqueue_script( 'wp-api-fetch' ); // or use below when enqueueing as dependency //wp_enqueue_script( 'my_script', 'path/to/my/script', array( 'wp-api-fetch' ) ); -
And just call
wp.apiFetch()like so:wp.apiFetch( { path: '/wp/v2/posts?per_page=2' } ).then( function( posts ){ console.log( 'Title of the first item is: ' + posts[0].title.rendered ); } );pathis a REST API route like/wp/v2/postswhich can optionally be appended with one or more arguments for that specific route.
How can I get a list of all the posts for selection within the editor
If you’re on the admin screen for editing or creating a post, then the wp-api-fetch script has already been enqueued if the block editor is enabled for that post. And if you’re specifically creating a block, then you can actually use getEntityRecords() along with withSelect (for listening to state changes). See the Latest Posts block for sample implementation.