如何使用 WordPress posts API 來新增文章呢?
可以先參考官方資料:
https://developer.wordpress.org/rest-api/reference/posts/#create-a-post
而 API的位置在: https://{hostname}/wp/v2/posts
而新增一篇文章的方式有了這些資料就可以很快速地建立起來, 另外我們還需要先有一個 application password 來進行驗證才行, 在 WordPress 5.6 版本起, 可以在使用者下建立 application password, 所以可以透過這個方式來進行驗證, 可以參考這裡:
https://make.wordpress.org/core/2020/11/05/application-passwords-integration-guide/
有了帳號, application password 就可以來進行文章的新增了. 這裡有參考範例:
https://blog.finxter.com/how-to-publish-a-wordpress-post-using-python/
import requests
import json
# The URL for the API endpoint
url = 'http://your-site-url/wp-json/wp/v2/posts'
# Your WordPress username
username = 'your-username'
# The application password you generated
password = 'your-application-password'
# The post data
data = {
'title': 'My New Post',
'content': 'This is the content of my new post.',
'status': 'publish' # Use 'draft' to save the post as a draft
}
# Send the HTTP request
response = requests.post(url, auth=(username, password), json=data)
# Check the response
if response.status_code == 201:
print('Post created successfully')
else:
print('Failed to create post: ' + response.text)
其中若是需要新增分類, 標籤, 可以先檢查原來在網站中的分類與標籤代碼, 如何找到代碼? 可以參考這篇:
然而可能會需要同時多個分類或多個標籤, 必須傳入字串的方式來進行:
有了這些資訊後, 相信對於利用 Python 來透過 WordPress API 新增文章應該就可以完成了.