什么是WordPress REST API
WordPress REST API是現(xiàn)代WordPress開(kāi)發(fā)的核心功能之一,它允許開(kāi)發(fā)者通過(guò)HTTP請(qǐng)求與WordPress站點(diǎn)進(jìn)行交互。這個(gè)基于JSON的API為開(kāi)發(fā)者提供了創(chuàng)建、讀取、更新和刪除(CRUD)WordPress內(nèi)容的能力,包括文章、頁(yè)面、評(píng)論、用戶(hù)等幾乎所有WordPress數(shù)據(jù)。
WordPress文章REST API基礎(chǔ)
WordPress文章REST API端點(diǎn)通常遵循以下格式:
/wp-json/wp/v2/posts
基本操作
- 獲取文章列表:
GET /wp-json/wp/v2/posts
- 獲取單篇文章:
GET /wp-json/wp/v2/posts/<id>
- 創(chuàng)建新文章:
POST /wp-json/wp/v2/posts
- 更新文章:
POST /wp-json/wp/v2/posts/<id>
- 刪除文章:
DELETE /wp-json/wp/v2/posts/<id>
認(rèn)證方式
WordPress REST API提供了幾種認(rèn)證方式:
- Cookie認(rèn)證:適用于瀏覽器環(huán)境
- OAuth認(rèn)證:推薦用于第三方應(yīng)用
- 應(yīng)用密碼:WordPress 5.6+引入的簡(jiǎn)單認(rèn)證方式
- JWT認(rèn)證:通過(guò)插件實(shí)現(xiàn)的JSON Web Token認(rèn)證
實(shí)際應(yīng)用示例
獲取文章列表
fetch('https://your-site.com/wp-json/wp/v2/posts')
.then(response => response.json())
.then(posts => console.log(posts));
創(chuàng)建新文章
fetch('https://your-site.com/wp-json/wp/v2/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN'
},
body: JSON.stringify({
title: '新文章標(biāo)題',
content: '文章內(nèi)容...',
status: 'publish'
})
})
.then(response => response.json())
.then(post => console.log('創(chuàng)建成功:', post));
高級(jí)查詢(xún)參數(shù)
WordPress文章REST API支持多種查詢(xún)參數(shù):
per_page
: 每頁(yè)顯示數(shù)量page
: 頁(yè)碼search
: 搜索關(guān)鍵詞after/berfore
: 按日期篩選categories
: 按分類(lèi)篩選tags
: 按標(biāo)簽篩選orderby
: 排序字段order
: 排序方式(asc/desc)
示例:
/wp-json/wp/v2/posts?categories=5&per_page=10&orderby=date&order=desc
自定義字段支持
要處理自定義字段,需要先注冊(cè)字段或使用ACF等插件提供的REST API支持:
// 在主題的functions.php中注冊(cè)自定義字段
add_action('rest_api_init', function() {
register_rest_field('post', 'custom_field', array(
'get_callback' => function($post_arr) {
return get_post_meta($post_arr['id'], 'custom_field', true);
},
'update_callback' => function($value, $post) {
update_post_meta($post->ID, 'custom_field', $value);
},
'schema' => array(
'description' => '自定義字段描述',
'type' => 'string'
)
));
});
性能優(yōu)化建議
- 使用
_fields
參數(shù)只請(qǐng)求需要的字段 - 合理使用緩存
- 限制每頁(yè)返回?cái)?shù)量
- 考慮使用GraphQL作為替代方案處理復(fù)雜查詢(xún)
常見(jiàn)問(wèn)題解決
- 403禁止訪問(wèn)錯(cuò)誤:檢查認(rèn)證是否正確
- 404端點(diǎn)不存在:確保WordPress版本支持REST API
- CORS問(wèn)題:添加適當(dāng)?shù)腃ORS頭
- 性能問(wèn)題:優(yōu)化查詢(xún),減少請(qǐng)求數(shù)據(jù)量
結(jié)語(yǔ)
WordPress文章REST API為開(kāi)發(fā)者提供了強(qiáng)大的內(nèi)容管理能力,無(wú)論是構(gòu)建移動(dòng)應(yīng)用、單頁(yè)應(yīng)用(SPA)還是與其他系統(tǒng)集成,都能發(fā)揮重要作用。掌握REST API的使用可以大大擴(kuò)展WordPress的應(yīng)用場(chǎng)景,為現(xiàn)代Web開(kāi)發(fā)提供更多可能性。