文章目录                    
                展开            
            
之前在介绍WordPress应用程序密码(application passwords)时VPS GO有说过这个程序密码的一大用处就是授权REST API,今天就给大家介绍下WordPress REST API的用法,利用Python来新建、更新、删除文章。
一、申请WordPress应用程序密码
WordPress应用程序密码不是登录密码,详细的介绍与申请方式可以参考之前VPS GO的分享:
二、使用REST API管理博客文章
这里直接分享Python版本的代码了,其他的代码可以在这个基础上自行修改。
首先需要导入需要的包:
import requests import json import base64
可以通过这个代码查看是否成功授权,reponse是否正确:
url = "https://example.com/wp-json/wp/v2/posts"
user = "your-username"
password = "your-application-password"
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
response = requests.get(url , headers=header)
print(response)
其中:
- example.com是你自己的域名
- user是你的登录名
- password是你刚才申请的应用程序密码
利用REST API新建文章代码:
url = "https://example.com/wp-json/wp/v2/posts"
user = "your-username"
password = "your-application-password"
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
post = {
'title' : 'Hello World',
'status' : 'publish',
'content' : 'This is my first post created using rest API',
'categories': 5, // category ID
'date' : '2020-01-05T10:00:00'
}
response = requests.post(url , headers=header, json=post)
print(response)
利用REST API更新文章代码:
url = "https://example.com/wp-json/wp/v2/posts/"
postID = 1
user = "your-username"
password = "your-application-password"
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
post = {
'title' : 'Hello World Updated',
'content' : 'This is my first post created using rest API Updated'
}
response = requests.post(url + postID , headers=header, json=post)
print(response)
利用REST API删除文章代码:
url = "https://example.com/wp-json/wp/v2/posts/"
user = "your-username"
password = "your-application-password"
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
response = requests.delete(url + postID , headers=header)
print(response)
以上就是WordPress REST API的使用方法了,除了这个接口外,WordPress还有xmlrpc接口,也可以操作文章:《Python 使用 xmlrpc 操作 WordPress:发布文章、新建标签和分类目录》