miguel.nz

WP Rest API filter example using objects

March 2, 2016   |   1 minute read.

Here we have an example of a request using filters from the WP Rest API 2.0:

var args = {
 posts_per_page: 2
 }

request('/wp-json/wp/v2/posts?' + filterify(args) ).then( function(result){
 console.log(result);
 })

 

In the snippet above request is just function I’ve created to handle XMLHttpRequests and in this case I want to get my last two posts. I’m not going to explain to do your requests, or how to getting started with the WP Rest API, but share how filterify works so you can easily create filters based in objects:

function filterify(obj) {
  var str = [];

    for(var p in obj) {
      if (obj.hasOwnProperty(p)) {
        var k = p, v = obj[p];
        str.push(typeof v == "object" ? serialize(v, k) : 'filter[' + encodeURIComponent(k) + ']' + "=" + encodeURIComponent(v));
      }
    }

  return str.join("&");
}

Now our request is ready to work as it follows this format: /wp-json/wp/v2/blog?filter[posts_per_page]=2.

Happy filtering!