右侧显示信息
广告位 后台主题配置管理

网站首页 > zblog专区 正文

WordPress使用REST API新建、更新、删除文章教程(Python代码)

w227 2023-03-13 11:05:56 zblog专区 3093 ℃
广告位 后台主题配置管理

转载自https://www.vpsgo.com/wordpress-manage-posts-with-rest-api-using-python.html

之前在介绍WordPress应用程序密码(application passwords)时VPS GO有说过这个程序密码的一大用处就是授权REST API,今天就给大家介绍下WordPress REST API的用法,利用Python来新建、更新、删除文章。

一、申请WordPress应用程序密码

WordPress应用程序密码不是登录密码,详细的介绍与申请方式可以参考之前VPS GO的分享:

《WordPress应用程序密码(application passwords)设置教程》

二、使用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/post"
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接口,自行百度

联系我们
付费后若不能复制,请刷新页面重试。 如有问题,再加客服微信。 工作日上午8:30-11:30 14:30-17:30
免费复制
微信扫码领取验证码
注:需在公众号回复"验证码"
输入验证码后可以免费复制
付费复制 免费复制 付费复制
付费30天内免费复制

价格:2.99元

支付宝支付
扫一扫,支付¥2.99

正在加载二维码...

支付完成后,请等待10秒左右,请勿关闭此页
请在这里放置你的在线分享代码
最近发表
标签列表
最新留言