Add custom post type to Backbone collections

Excerpt from the documentation: (scroll down to the “Working With Revisions” section on that page)

Note: Because the schema is stored in the user’s session cache to
avoid re-fetching, you may need to open a new tab to get a new read of
the Schema.

So it’s probably just a caching issue and you only needed to open a new (browser) tab, or test your code in another tab or window.

However, if you don’t want to having to open another tab/window, then you can force the browser to delete the session cache for the schema right after WordPress defined the wpApiSettings variable which is when the wp-api-request script (wp-includes/js/api-request.js) is enqueued.

So for that purpose, you can use wp_add_inline_script():

// Enqueue the Backbone client library.
wp_enqueue_script( 'wp-api' ); // this includes the wp-api-request (api-request.js) script

// And then delete the session cache. Note: Don't include the <script> and </script> tags!
wp_add_inline_script( 'wp-api-request', "try { sessionStorage.removeItem( 'wp-api-schema-model' + wpApiSettings.root + wpApiSettings.versionString ); } catch ( err ) {}" );

But then, I’m not recommending the above — the schema is already quite a lot by default and it could take some time for the browser to request the schema and then process it via the Backbone client. But I shared the code as an option if you absolutely must reset the cache every time the page is loaded. Secondly, you can use the above code to confirm that you had a caching issue.

And by the way, apart from the Backbone client, you can actually use wp.apiRequest() to make request to the REST API endpoints:

  • PHP: wp_enqueue_script( 'wp-api-request' );

  • JavaScript examples for a post type having custom as the slug:

    // Fetch a collection (i.e. a list of posts).
    wp.apiRequest( { path: 'wp/v2/custom' } )
      .then( posts => console.log( posts ) );
    
    // Create a model/post.
    wp.apiRequest( {
      path: 'wp/v2/custom',
      method: 'POST',
      data: {
        title: 'New Custom Post',
        content: 'Just testing',
        // ..other data, if any..
      }
    } ).then( post => console.log( post ) );
    
    // Update a model/post.
    wp.apiRequest( {
      path: 'wp/v2/custom/123', // change 123 to the correct ID
      method: 'POST',
      data: {
        title: 'New Title',
        // ..other data you want to UPDATE
      }
    } ).then( post => console.log( post ) );
    
    // Destroy a model/post.
    wp.apiRequest( {
      path: 'wp/v2/custom/123', // change 123 to the correct ID
      method: 'DELETE'
    } ).then( post => console.log( post.status ) ); // 'trash'