WordPress REST API為開發(fā)者提供了通過(guò)HTTP請(qǐng)求與WordPress站點(diǎn)交互的強(qiáng)大方式。本文將介紹如何使用JavaScript通過(guò)WordPress REST API進(jìn)行基本操作。
準(zhǔn)備工作
在使用WordPress REST API前,需要確保:
- 使用WordPress 4.7或更高版本
- 已啟用REST API功能(默認(rèn)啟用)
- 了解基本的JavaScript和AJAX知識(shí)
基本請(qǐng)求結(jié)構(gòu)
WordPress REST API的基本端點(diǎn)格式為:
https://your-wordpress-site.com/wp-json/wp/v2/
例如獲取文章列表:
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts')
.then(response => response.json())
.then(posts => console.log(posts));
認(rèn)證方式
對(duì)于需要認(rèn)證的操作(如創(chuàng)建、更新、刪除內(nèi)容),WordPress提供了幾種認(rèn)證方式:
- Cookie認(rèn)證:適用于已登錄用戶
- OAuth:更安全的第三方應(yīng)用認(rèn)證
- 應(yīng)用密碼:WordPress 5.6+引入的簡(jiǎn)單認(rèn)證方式
常見操作示例
1. 獲取文章
// 獲取最新5篇文章
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts?per_page=5')
.then(response => response.json())
.then(posts => {
posts.forEach(post => {
console.log(post.title.rendered);
});
});
2. 創(chuàng)建新文章
const newPost = {
title: '我的新文章',
content: '這是通過(guò)REST API創(chuàng)建的文章內(nèi)容',
status: 'publish'
};
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_APPLICATION_PASSWORD'
},
body: JSON.stringify(newPost)
})
.then(response => response.json())
.then(post => console.log('創(chuàng)建成功:', post));
3. 更新文章
const updatedPost = {
title: '更新后的標(biāo)題'
};
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts/123', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_APPLICATION_PASSWORD'
},
body: JSON.stringify(updatedPost)
})
.then(response => response.json())
.then(post => console.log('更新成功:', post));
4. 刪除文章
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts/123', {
method: 'DELETE',
headers: {
'Authorization': 'Bearer YOUR_APPLICATION_PASSWORD'
}
})
.then(response => {
if(response.ok) {
console.log('刪除成功');
}
});
錯(cuò)誤處理
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts/999')
.then(response => {
if(!response.ok) {
throw new Error('請(qǐng)求失敗: ' + response.status);
}
return response.json();
})
.then(post => console.log(post))
.catch(error => console.error('錯(cuò)誤:', error));
自定義端點(diǎn)
如果需要擴(kuò)展API,可以在主題的functions.php中添加自定義端點(diǎn):
add_action('rest_api_init', function() {
register_rest_route('myplugin/v1', '/custom-endpoint', array(
'methods' => 'GET',
'callback' => 'my_custom_endpoint_handler'
));
});
function my_custom_endpoint_handler($data) {
return array('message' => '這是自定義端點(diǎn)');
}
然后通過(guò)JavaScript調(diào)用:
fetch('https://your-wordpress-site.com/wp-json/myplugin/v1/custom-endpoint')
.then(response => response.json())
.then(data => console.log(data));
最佳實(shí)踐
- 始終在生產(chǎn)環(huán)境使用HTTPS
- 合理限制API訪問權(quán)限
- 使用緩存減少服務(wù)器負(fù)載
- 考慮使用wp-api JavaScript庫(kù)簡(jiǎn)化操作
通過(guò)掌握這些基礎(chǔ)知識(shí),您可以開始使用JavaScript通過(guò)REST API與WordPress站點(diǎn)進(jìn)行交互,創(chuàng)建更動(dòng)態(tài)、響應(yīng)式的Web應(yīng)用。