Last active
January 6, 2016 05:33
-
-
Save adamsilverstein/edc719146b1b4c3074fb to your computer and use it in GitHub Desktop.
Create a post with categories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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