0

I'm trying to create a custom block but I need some assistance.

I'm attempting to setup a <select> in the editor that lists all the posts. I'm not very experienced at the api yet but after reading the docs, it seems that the below line should work to get the posts.

wp.api.collections.Posts().fetch()

The problem is, however, I'm getting a nice error of:

TypeError: Cannot read property 'collections' of undefined

How can I get a list of all the posts for selection within the editor, or is it just outside the realm of possibility?

1

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:

  1. Enqueue the wp-api-fetch script:

    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' ) );
    
  2. 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 );
    } );
    

    path is a REST API route like /wp/v2/posts which 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.

1

You need to enqueue WP API javascript, You should have added above code in one of your custom files, support your file name is myscript.js

And you should have queued it somewhere, modify that and attach wp-api as a dependency like this :

wp_enqueue_script( 'my_script', 'path/to/my/myscript.js', array( 'wp-api' ) );
  • Added wp-api as a dependency, thanks. Now I'm getting new errors on the same line though TypeError: this._reset is not a function. Any ideas? – Spedwards Aug 5 at 18:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.