如何使用REST API发布文章到Wordpress?
步骤#01:安装JWT插件,获取Token
详细步骤参照这篇文章
安装完以后,就可以使用Python代码获取token了。
def get_token():
session = requests.Session()
url = 'https://youdomain.com/wp-json/jwt-auth/v1/token'
data = {
'username':"user_login_name",
'password':"user_login_password"
}
headers = {'user-agent': 'Mozolla/5.0',
}
resp = session.post(url, data=data, headers=headers, timeout=3335) # 请求
r = json.loads(resp.content)
return r
url = ‘https://youdomain.com/wp-json/jwt-auth/v1/token’ 改为自己的网址,比如自己的域名是www.ensky.tech,则替换为url = ‘https://www.ensky.tech/wp-json/jwt-auth/v1/token’
步骤#02:发布文章
代码如下
def _do_post( wp_post_date, post_slug, post_title, post_content, token =''):
final_post_status=""
post_categories="1"
session = requests.Session()
url = 'https://youdomain.com//wp-json/wp/v2/posts'
data = {
#'date': datetime.datetime(2023, 6, 11).strftime('%Y-%m-%dT%H:%M:%SZ'),
'date': wp_post_date, #'2023-04-22T01:15:00Z',
'slug': post_slug, #'xx23',
'status': 'publish',
'password': '',
'title': post_title, #'4.22号1.15分发布 ',
'content': post_content, #'我是内容,哈哈哈,来自ensky.tech',
'author ': "", #'[email protected]',
'excerpt': '',
'featured_media': '0',
'comment_status': 'open',
'ping_status': 'closed',
'format': 'standard',
'meta': [],
'sticky': False, # 置顶
'template': '',
'categories': post_categories, # 1 未分类
'tags': ''
}
headers = {'user-agent': 'Mozolla/5.0',
'Authorization': 'Bearer ' + token
}
resp = session.post(url, data=data, headers=headers, timeout=3335) # 请求
post_respons_text=resp.text
#打印POST返回等详细信息
#print (post_respons_text)
post_json=json.loads(post_respons_text)
current_post_id=post_json['id']
print("current_post_id is: ")
print(current_post_id)
if __name__=='__main__':
now = datetime.utcnow()
wp_post_date = now.strftime('%Y-%m-%dT%H:%M:%SZ')
post_slug="the_first_article"
post_title="我是标题001"
post_content="我是内容001"
token="eyJ0eXAiOiJKV1J0eXAiOiJKV1LZVcueyJ0eXAiOiJKV1LZVcu"
_do_post( wp_post_date, post_slug, post_title, post_content, token)
status:可以一直使用publish
date:如果时间超过了网站时间,则会改为“计划发布”。如果将Date这一项删除,则会立刻发布文章。
Leave a Reply