-
Notifications
You must be signed in to change notification settings - Fork 191
Home
Query Methodology
node-wp-api is intended to do two things:
- build queries for the WordPress API,
- 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
Queries for alternate resources are possible:
wp.taxonomies().then(function( taxonomies ) {
taxonomies.forEach(function( tax ) {
console.log( tax.slug );
});
});
wp.users().me().get(function( err, data ) {
if ( ! err ) {
console.log("I am " + data.nicename;
}
});
Each of these methods, posts
, pages
, users
, media
, etc, will instantiate a new query object with a custom constructor inheriting from a common wpQuery object. wpQuery
will be responsible for building query parameter strings from the query objects' options hashes, while the child query constructors will handle defining the endpoint against which the request is to be made.