Monday, 7 August 2017

Using the WooCommerce API with wp-api.js

As of WordPress 4.7, we’ve had a really fantastic, fully featured REST API in WordPress. It is relatively well-known that the infrastructure for the API was introduced in WordPress 4.4, with the content endpoints being introduced in 4.7. What is somewhat less well-known is that 4.7 also shipped with a Backbone.js client you can use to interface with the core API. It’s super simple to enqueue:
wp_enqueue_script( ‘wp-api’ );
Using it for core objects is pretty straight-forward:
var post – new wp.api.models.Post( { id : 2 } );post.fetch();alert( post.attributes.title.rendered ); // Renders "rendered" title of post.
But what if you want to use it with non-core objects that are in custom namespaces, or maybe not even on your own site? Thinking that you’ll probably have to write some PHP, maybe your own library or framework for interfacing with these, and your own JS models? Ugh, amirite?
Good news! None of that is necessary.
Because of how well-architected the Backbone.js client is (massive shoutout to Adam Silverstein and all the other contributors), you can pretty easily access your custom endpoints and namespaces without writing much code at all. It can be


No comments:

Post a Comment