Search code examples
wordpressrestwp-api

How to make WordPress Rest API parameters accessible without authentication?


How can I make certain parameters of the WordPress Rest API accessible to anyone without first being authenticated – for example, the page parameter doesn't work (where blog is a custom post type) in this query:

mysite.com/wp-json/wp/v2/blog?page=2&per_page=20

I've seen that in the past it's been possible to make these params available, for instance :

add_filter( 'json_query_vars', function( $valid_vars ) {

    $valid_vars[] = 'offset';

    return $valid_vars;
});

Is there any way to do something similar with today's version of the API?


Solution

  • For anyone who has the same problem, I've solved it. The page parameter is actually publicly available, offset is the one you need authentication for.

    The reason the API didn't paginate was because the request url didn't have the paged query string set. Every time I tried to add it with the params option of the WordPress Node API, it didn't work:

    wpapi.getNews().params('paged', 'paged').perPage( perPage ).page( pageNumber ).then(data=>

    It didn't work because the request url created by the API seemed to always put the page parameter before the paged one, which resulted in paged being ignored when the query actually runs.

    So in the end, I created a custom query (bit of a hacked way to do it, but it worked) like so:

    Register the route:

    wpapi.getNews = wpapi.registerRoute('wp/v2', '/news/(?P<customQuery>)');

    Usage:

    wpapi.getNews().customQuery('?paged&per_page=20&page='+pageNumber).then(data =>

    Using the above, you can build any query, in any order you want. This helped me get the correctly paginated result. Also, we see 'getNews' here because I registered a route for accessing my custom post type called news.