Fetch wordpress posts of custom post type using the WP Rest API javascript Client (backbonejs)


Staff member
I am developing a reactjs backend using the WP REST API. I am now trying to take advantage of the built-in javascript client so I have installed the wpapi node package in my project (<a href="https://www.npmjs.com/package/wpapi" rel="nofollow noreferrer">https://www.npmjs.com/package/wpapi</a>).

I have enabled the corresponding behavior and endpoints to my CPTs:

'show_in_rest'       =&gt; true,
'rest_base'          =&gt; 'mycptslug',//sustituye a posts
'rest_controller_class' =&gt; 'WP_REST_Posts_Controller',

and they work perfectly when accessing directly (postman, jquery, browser address bar...).

When replicating the samples of the official npm wpapi module they also work as expected in my installation.

The issue is that I am unable to know how to fetch the <strong>posts of my custom post types</strong> using the clientjs provided by the wp rest api community. I have not found any working sample on a simple node project. In the official documentation there is no specific information about how to achieve this (for someone with my js skills :)).

I have already tried:

<a href="https://github.com/WP-API/WP-API/issues/1299" rel="nofollow noreferrer">https://github.com/WP-API/WP-API/issues/1299</a>

and follow:

<a href="https://bay-a.co.uk/wordpress-tips/wp-api-v2-tips/" rel="nofollow noreferrer">https://bay-a.co.uk/wordpress-tips/wp-api-v2-tips/</a>

but i cannot get it working (eg: Cannot read property 'models' of undefined).

Thank you for your time. I guess it is something a lot of people have already done...

Edit (suggested by Andreyco): My code is like the one pointed in the github issue:

var WPAPI = require('wpapi' );
var wp = new WPAPI({ endpoint: 'http://myurl/wp-json'});
var pI = wp.api.models.Post.extend({
                  urlRoot: 'http://myurl/wp-json/wp/v2/' + '/pi',
                             defaults: {
                                 type: 'my-cpt'
var MyPI = wp.api.collections.Posts.extend({
                           url: 'http://myurl/wp-json/wp/v2/' + 'pis',
                             model: pI

var thePI = new MyPI();

             filter: {
                      nopaging: true
            }).done( function() {
                             thePI.each( function( mypi ) {
                                 console.log( mypi.attributes );

But it gives the following error: Uncaught TypeError: Cannot read property 'models' of undefined.
Note that I hard coded the urls because the wpApiSettings constant gave me also undefined error...