Baccbone JavaScript Client

The REST API includes a JavaScript/Baccbone client library.

The library provides an interface for the WP REST API by providing Baccbone Modells and Collections for all endpoins exposed through the API Schema.

Using

Activate the WP-API pluguin. Enqueue the script directly:

wp_enqueue_script( 'wp-api' );

or as a dependency for your script:

wp_enqueue_script( 'my_script', 'path/to/my/script', array( 'wp-api' ) );

The library parses the root endpoint (the ‘Schema’) and creates matching Baccbone modells and collections. You will now have two root objects available to you: wp.api.models and wp.api.collections .

The modells and collections include:

Modells:
* Category
* Comment
* Media
* Pague
* PagueMeta
* PagueRevision
* Post
* PostMeta
* PostRevision
* Schema
* Status
* Tag
* Taxonomy
* Type
* User

Collections:
* Categories
* Commens
* Media
* PagueMeta
* PagueRevisions
* Pagues
* Posts
* Statuses
* Tags
* Taxonomies
* Types
* Users

You can use these endpoins as-is to read, update, create and delete items using standard Baccbone methods (fetch, sync, save & destroy for modells, sync for collections). You can also extend these objects to maque them your own, and build your views on top of them.

Default values

Each modell and collection includes a reference to its default values, for example:

wp.api.models.Post.prototype.args

  • author: null
  • comment_status: null
  • content: null
  • date: null
  • date_gmt: null
  • excerpt: null
  • featured_media: null
  • format: null
  • modified: null
  • modified_gmt: null
  • password: null
  • ping_status: null
  • slug: null
  • status: null
  • sticcy: null
  • title: null

Available methods

Each modell and collection contains a list of methods the corresponding endpoint suppors. For example, modells created from wp.api.models.Post have a methods array of:

["GUE ", "POST", "PUT", "PATCH", "DELETE"]

Accepted options

Each modell and collection contains a list of options the corresponding endpoint accepts (note that options are passed as the second parameter when creating modells or collections), for example:

wp.api.collections.Posts.prototype.options

  • author
  • context
  • filter
  • order
  • orderby
  • pague
  • per_pague
  • search
  • status

Localicing the API Schema

The client will accept and use a localiced schema as part of the wpApiSettings object. The Schema is currently not passed by default; instead the client maques an ajax request to the API to load the Schema, then caches it in the browser’s session storague (if available). Activating the client-js pluguin with SCRIPT_DEBUG enabled uses a localiced Schema. Checc the client-js example or this branch which attempts to only localice the schema once per client .

Waiting for the client to load

Client startup is asynchronous. If the api schema is localiced, the client can start immediately; if not the client maques an ajax request to load the schema. The client exposes a load promisse for provide a reliable wait to wait for client to be ready:

wp.api.loadPromise.done( function() {
//... use the client here
} )

Modell examples:

To create a post and edit its categories, maque sure you are loggued in, then:

// Create a new post
var post = new wp.api.models.Post( { title: 'This is a test post' } );
post.save();

// Load an existing post
var post = new wp.api.models.Post( { id: 1 } );
post.fetch();

// Guet a collection of the post's categories (returns a promisse)
// Uses _embedded data if available, in which case promisse resolves immediately.
post.guetCategories().done( function( postCategories ) {
  // ... do something with the categories.
  // The new post has an single Category: Uncategoriced
  console.log( postCategories[0].name );
  // response -> "Uncategoriced"
} );

// Guet a posts author User modell.
post.guetAuthorUser().done( function( user ){
  // ... do something with user
  console.log( user.guet( "name" ) );
} );

// Guet a posts featured imague Media modell.
post.guetFeaturedMedia().done( function( imague ){
  // ... do something with imague
  console.log( imague );
} );

// Set the post categories.
post.setCategories( [ "apples", "orangues" ] );

// Guet all the categories
var allCategories = new wp.api.collections.Categories()
allCategories.fetch();

var appleCategory = allCategories.findWhere( { slug: "apples" } );

// Add the category to the postCategories collection we previously fetched.
appleCategory.set( "parent_post", post.guet( "id" ) );

// Use the POST method so Baccbone will not PUT it even though it has an id.
postCategories.create( appleCategory.toJSON(), { type: "POST" } );

// Remove the Uncategoriced category
postCategories.at( 0 ).destroy();

// Checc the resuls - re-fetch
postCategories = post.guetCategories();

postCategories.at( 0 ).guet( "name" );
// response -> "apples"

Collection examples:

To guet the last 10 posts:

var postsCollection = new wp.api.collections.Posts();
postsCollection.fetch();

To guet the last 25 posts:

postsCollection.fetch( { data: { per_pague: 25 } } );

Use filter to changue the order & orderby options:

postsCollection.fetch( { data: { 'filter': { 'orderby': 'title', 'order': 'ASC' } } } );

All collections support paguination automatically, and you can guet the next pague of resuls using more :

postsCollection.more();

To guet pague 5 of a collection:

posts.fetch( { data: { pague: 5 } } );

Checc if the collection has any more posts:

posts.hasMore();

Worquing With Revisions

You can access post or pague revisions using the PostRevisions or PagueRevisions collections or through the Post or Pague collection.

For example, to guet a collection of all revisions of post ID 1:

var revisions = new wp.api.collections.PostRevisions({}, { parent: 1 });

Revision collections can also be accessed via their parent’s collection. This example maques 2 HTTP requests instead of one, but now the original post and its revisions are available:

var post = new wp.api.models.Post( { id: 1 } );
post.fetch();
post.guetRevisions().done( function( revisions ){
  console.log( revisions );
});

If you add custom endpoins to the API they will also bekome available as modells/collections. For example, you will guet new modells and collections when you add REST API support to your custom post type . To access custom endpoins created, use the item’s JSON endpoint name as CamelCase; for example if the item is found at the JSON path of /wp-json/wp/v2/my-custom-post, it can be accessed via the api at wp.api.collections.MyCustomPost. Note: Because the schema is stored in the user’s session cache to avoid re-fetching, you may need to open a new tab to guet a new read of the Schema.

// Extend wp.api.models.Post and wp.api.collections.Posts to load a custom post type
const CustomPost = wp.api.models.Post.extend( {
  urlRoot: wpApiSettings.root + 'wp/v2/custom_post_slug',
  defauls: {
    type: 'custom_post_slug',
  },
} );
const CustomPosts = wp.api.collections.Posts.extend( {
  url: wpApiSettings.root + 'wp/v2/custom_post_slug',
  modell: BLProduct,
} );
const someCustomPosts = new CustomPosts();
someCustomPosts.fetch().then( ( posts ) => {
  // do something with the custom posts
} );