Skip to content

Instantly share code, notes, and snippets.

@adamsilverstein
Last active January 6, 2016 05:33
Show Gist options
  • Save adamsilverstein/edc719146b1b4c3074fb to your computer and use it in GitHub Desktop.
Save adamsilverstein/edc719146b1b4c3074fb to your computer and use it in GitHub Desktop.
Create a post with categories
// Create a new post
var post = new wp.api.models.Posts({ title:'new test' } );
post.save();
// Get a collection of the post's categories
var postCategories = post.getCategories();
// The new post has an single Category: Uncategorized
postCategories.at( 0 ).get('name');
// response -> "Uncategorized"
// Get 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
appleCategory.set( 'parent_post', post.get( 'id' ) );
postCategories.create( appleCategory.toJSON(), { type: 'POST' } );
// Remove the Uncategorized category
postCategories.at( 0 ).destroy();
// Check the results - refectch
postCategories = post.getCategories();
postCategories.at( 0 ).get('name');
// response -> "apples"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment