Skip to content
K.Adam White edited this page Jun 3, 2014 · 2 revisions

Query Methodology

node-wp-api is intended to do two things:

  1. build queries for the WordPress API,
  2. execute those queries to access, create, modify or remove data via the API

As an example, this is how we envision a request for the 20 most recent posts by a specific author to look:

const WP_API = require('wp-api');
var wp = new WP_API({
  endpoint: 'http://www.mywordpresswebsite.com/wp-json'
});

// Build a query for Posts resources
var postsQuery = wp.posts()
  // Use the WP_Query posts_per_page property to modify the query:
  // This will set a query parameter of `filter[posts_per_page]=20` at
  // the end of the HTTP request generated when this query is submitted
  .filter( 'posts_per_page', 20 )
  // Or set multiple params at once by passing an object, à la jQuery's methods
  .filter({
    // This could have as many key-value pairs as needed
    authorname: 'matt'
  });

We cached the query in a postsQuery object to demonstrate multiple ways to proceed from this point. The query is latent until submitted, so we could continue to chain filter methods onto the query; whenever it is ready, it can be submitted in either a callback or promise-style syntax.

// All of these should work
postsQuery.get(function( err, data ) {}); // GET, then trigger a callback fn
postsQuery.then(function( data ) {}, function( err ) {}); // Defaults to GET
postsQuery.get().then(function( data ) {}, function( err ) {}); // Specify GET explicitly
Clone this wiki locally