How to return a list of custom taxonomy terms via the Gutenberg getEntityRecords method

  1. The getEntityRecords() method uses the REST API, so make sure the taxonomy is enabled for the REST API. You can enable it via the show_in_rest parameter when registering the taxonomy using register_taxonomy().

  2. With getEntityRecords(), if you set per_page to -1, it will actually be changed to 100, which as you’ve figured it out, is the max number of results returned for a single API request (details here). Hence that’s why per_page: -1 should work with getEntityRecords().

  3. Any AJAX/remote requests would not give you immediate results and we would need to wait a moment until the browser receives the response from the server. So this is probably the actual reason to why you’re not getting any results immediately upon first call to getEntityRecords().

With that said, on subsequent calls (for the same query), you should get immediate results because getEntityRecords() cache the results (for performance reasons — you wouldn’t want each call to getEntityRecords() takes several seconds to give you the results, would you?).

So try:

  1. wp.apiFetch() which is used by getEntityRecords(): Both these work; apiFetch() makes request to http://example.com/wp-json/wp/v2/your_tax?per_page=100:

    wp.apiFetch( { path: '/wp/v2/your_tax?per_page=-1' } )
        // 'terms' contains valid term objects
        .then( terms => console.log( terms ) );
    
    wp.apiFetch( { path: '/wp/v2/your_tax?per_page=100' } )
        // 'terms' contains valid term objects
        .then( terms => console.log( terms ) );
    
  2. fetch() which is used internally by wp.apiFetch():

    fetch( '/wp-json/wp/v2/your_tax?per_page=-1' )
        .then( res => res.json() )
        // 'terms' contains an error about per_page should be between 1 and 100
        .then( terms => console.log( terms ) );
    
    fetch( '/wp-json/wp/v2/your_tax?per_page=100' )
        .then( res => res.json() )
        // 'terms' contains valid term objects
        .then( terms => console.log( terms ) );
    

So if you make manual requests to /wp-json/wp/v2/your_tax (i.e. a taxonomy terms REST API), then you should not set the per_page to -1. But with wp.apiFetch() and functions which uses apiFetch() like getEntityRecords(), you can use that -1 although you should not

Leave a Comment