> For the complete documentation index, see [llms.txt](https://learnphp.gitbook.io/learnphp/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://learnphp.gitbook.io/learnphp/wordpress/api-backbone-javascript-client.md).

# \[API] Backbone JavaScript Client

API REST bao gồm thư viện máy khách JavaScript / Backbone.

Thư viện cung cấp giao diện cho API WP REST bằng cách cung cấp Mô hình xương sống và Bộ sưu tập cho tất cả các điểm cuối được hiển thị thông qua Lược đồ API.

### Using [#Using](https://developer.wordpress.org/rest-api/using-the-rest-api/backbone-javascript-client/#using) <a href="#using" id="using"></a>

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

&#x20;`wp_enqueue_script(` `'wp-api'` `);`

or as a dependency for your script:

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

Thư viện phân tích cú pháp điểm cuối gốc (‘Lược đồ’) và tạo các mô hình và bộ sưu tập Backbone phù hợp. Bây giờ bạn sẽ có sẵn hai đối tượng gốc: wp.api.models và wp.api.collections.

The models and collections include:

Models:\
\* Category\
\* Comment\
\* Media\
\* Page\
\* PageMeta\
\* PageRevision\
\* Post\
\* PostMeta\
\* PostRevision\
\* Schema\
\* Status\
\* Tag\
\* Taxonomy\
\* Type\
\* User

Collections:\
\* Categories\
\* Comments\
\* Media\
\* PageMeta\
\* PageRevisions\
\* Pages\
\* Posts\
\* Statuses\
\* Tags\
\* Taxonomies\
\* Types\
\* Users

Bạn có thể sử dụng các điểm cuối này để đọc, cập nhật, tạo và xóa các mục bằng cách sử dụng các phương pháp Backbone tiêu chuẩn (tìm nạp, đồng bộ hóa, lưu và hủy cho các mô hình, đồng bộ cho bộ sưu tập). Bạn cũng có thể mở rộng các đối tượng này để biến chúng thành của riêng bạn và xây dựng các quan điểm của bạn trên chúng.

#### Default values <a href="#default-values" id="default-values"></a>

Mỗi mô hình và bộ sưu tập bao gồm một tham chiếu đến các giá trị mặc định của nó, ví dụ:

`wp.api.models.Post.prototype.args`

* author: null
* comment\_status: null
* content: null
* date: null
* date\_gmt: null
* excerpt: null
* featured\_image: null
* format: null
* modified: null
* modified\_gmt: null
* password: null
* ping\_status: null
* slug: null
* status: null
* sticky: null
* title: null

#### Available methods <a href="#available-methods" id="available-methods"></a>

Mỗi mô hình và bộ sưu tập chứa một danh sách các phương thức mà điểm cuối tương ứng hỗ trợ. Ví dụ: các mô hình được tạo từ wp.api.models.Post có một mảng phương thức:

&#x20;`["GET",` `"POST",` `"PUT",` `"PATCH",` `"DELETE"]`

#### Accepted options <a href="#accepted-options" id="accepted-options"></a>

Mỗi mô hình và bộ sưu tập chứa danh sách các tùy chọn mà điểm cuối tương ứng chấp nhận (lưu ý rằng các tùy chọn được chuyển làm tham số thứ hai khi tạo mô hình hoặc bộ sưu tập), ví dụ:

`wp.api.collections.Posts.prototype.options`

* author
* context
* filter
* order
* orderby
* page
* per\_page
* search
* status

#### Waiting for the client to load <a href="#waiting-for-the-client-to-load" id="waiting-for-the-client-to-load"></a>

Khởi động máy khách không đồng bộ. Nếu lược đồ api được bản địa hóa, máy khách có thể bắt đầu ngay lập tức; nếu không, khách hàng thực hiện một yêu cầu ajax để tải lược đồ. Khách hàng đưa ra một lời hứa tải để cung cấp một thời gian chờ đáng tin cậy để đợi khách hàng sẵn sàng:

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

#### Model examples: <a href="#model-examples" id="model-examples"></a>

Để tạo một bài đăng và chỉnh sửa các danh mục của nó, hãy đảm bảo rằng bạn đã đăng nhập, sau đó:

```
// 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();
 
// Get a collection of the post's categories (returns a promise)
// Uses _embedded data if available, in which case promise resolves immediately.
post.getCategories().done( function( postCategories ) {
  // ... do something with the categories.
  // The new post has an single Category: Uncategorized
  console.log( postCategories[0].name );
  // response -> "Uncategorized"
} );
 
// Get a posts author User model.
post.getAuthorUser().done( function( user ){
  // ... do something with user
  console.log( user.get( "name" ) );
} );
 
// Get a posts featured image Media model.
post.getFeaturedMedia().done( function( image ){
  // ... do something with image
  console.log( image );
} );
 
// Set the post categories.
post.setCategories( [ "apples", "oranges" ] );
 
// 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 we previously fetched.
appleCategory.set( "parent_post", post.get( "id" ) );
 
// Use the POST method so Backbone will not PUT it even though it has an id.
postCategories.create( appleCategory.toJSON(), { type: "POST" } );
 
// Remove the Uncategorized category
postCategories.at( 0 ).destroy();
 
// Check the results - re-fetch
postCategories = post.getCategories();
 
postCategories.at( 0 ).get( "name" );
// response -> "apples"
```

#### Collection examples <a href="#collection-examples" id="collection-examples"></a>

To get the last 10 posts:

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

To get the last 25 posts:

```
postsCollection.fetch( { data: { per_page: 25 } } );
```

Use filter to change the order & orderby options:

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

&#x20;All collections support pagination automatically, and you can get the next page of results using `more`:

```
postsCollection.more();
```

To get page 5 of a collection:

```
posts.fetch( { data: { page: 5 } } );
```

Check if the collection has any more posts:

```
posts.hasMore();
```

#### Working With Revisions <a href="#working-with-revisions" id="working-with-revisions"></a>

You can access post or page revisions using the PostRevisions or PageRevisions collections or through the Post or Page collection.

For example, to get 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 makes 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.getRevisions().done( function( revisions ){
  console.log( revisions );
});
```

If you add custom endpoints to the API they will also become available as models/collections. For example, you will get new models and collections when you [add REST API support to your custom post type](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-rest-api-support-for-custom-content-types/). 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 get 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',
  defaults: {
    type: 'custom_post_slug',
  },
} );
const CustomPosts = wp.api.collections.Posts.extend( {
  url: wpApiSettings.root + 'wp/v2/custom_post_slug',
  model: BLProduct,
} );
const someCustomPosts = new CustomPosts();
someCustomPosts.fetch().then( ( posts ) => {
  // do something with the custom posts
} );
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learnphp.gitbook.io/learnphp/wordpress/api-backbone-javascript-client.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
