0

I’m making a webapp based on wordpress in which I’m using the REST API for my users to get and create posts.

I found the very useful REST API backbone javascript client which seems great. However the documentation in this link is limited to only a few selected examples. Is there a more complete documentation? With more examples?

I'm trying to filter posts by author and status. To display current user's drafts and published posts in different places.

How do you use the 'options'? I can't understand where to filter by the author nor status. For the author I tried a lot of variations like this one but it always return all the posts.

new wp.api.collections.Posts( { data: { 'author': { 'id': '1' }} } ).fetch().then( posts => { 
    for(const post of posts){
        //do stuff with post
    }
} );

Beside if I leave out options, it doesn't return the draft posts, only published posts. Thanks!!

3
  • 1
    If you look at the collection examples, the options are actually passed to the fetch() method and not the constructor. So for example, ( new wp.api.collections.Posts() ).fetch( { data: { author: 1 } } )
    – Sally CJ
    Sep 10, 2021 at 14:06
  • @SallyCJ Oh thanks so much!! I spent so much time on that thing... By the way do you know how to update a post? It says that 'wp.api.models.Post have a methods array of: ["GET", "POST", "PUT", "PATCH", "DELETE"]' But I don't know how to use that "PUT". And trying to save with the post.id result in forbidden error. Sep 10, 2021 at 14:36
  • 1
    Never mind I found how. Thanks again. Sep 10, 2021 at 14:44

1 Answer 1

1

Thanks @sallyCJ for fixing my error ! Here's some examples for WP-API backbone JS client. It may help others :

Fetch post of a certain author and category :

var filteredPosts = new wp.api.collections.Posts();
authorsPosts.fetch({ data: { author: currentUserId, categories: 42 } }).then( posts => { 
    for(const post of posts){
        //do stuff with each post
    }
} );

Update a post :

var post = new wp.api.models.Post( { 
    id: idOfThePostYouWantToUpdate,
    title: newTitle,
    content: newContent,
    status: newStatus,
    categories: [ 42 ],
    tags: [ 50 ]
    });
post.save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.