在本指南中,我們將探討如何使用 WordPress API 進行驗證並安排特定發佈時間的貼文。這些步驟將幫助您以程式設計方式安全地管理您的 WordPress 內容。
要安全地與 WordPress API 交互,您需要對您的要求進行身份驗證。讓我們深入研究兩種常見的方法:
應用程式密碼是 WordPress 中的內建功能,可讓您產生用於 API 存取的安全密碼,而不會洩露您的主帳戶密碼。
使用應用程式密碼:
import requests
url = "https://your-wordpress-site.com/wp-json/wp/v2/posts"
username = "your_username"
app_password = "your_application_password"headers = {
"Content-Type": "application/json"
}response = requests.get(url, auth=(username, app_password), headers=headers)
對於較舊的 WordPress 版本或如果您喜歡替代方法:
import requests
url = "https://your-wordpress-site.com/wp-json/wp/v2/posts"
username = "your_username"
password = "your_password"headers = {
"Content-Type": "application/json"
}response = requests.get(url, auth=(username, password), headers=headers)
若要安排貼文在特定時間發布,請在建立或更新貼文時使用日期參數。方法如下:
import requests
from datetime import datetime, timedeltaurl = "https://your-wordpress-site.com/wp-json/wp/v2/posts"
username = "your_username"
app_password = "your_application_password"# Schedule the post for 2 days from now at 10:00 AM
scheduled_time = datetime.now() timedelta(days=2)
scheduled_time = scheduled_time.replace(hour=10, minute=0, second=0, microsecond=0)
scheduled_time_str = scheduled_time.isoformat()data = {
"title": "Scheduled Post Example",
"content": "This is the content of the scheduled post.",
"status": "future",
"date": scheduled_time_str
}response = requests.post(url, auth=(username, app_password), json=data)
if response.status_code == 201:
print("Post scheduled successfully!")
else:
print("Error scheduling post:", response.text)
要重新安排現有帖子,您需要其帖子 ID:
import requests
from datetime import datetime, timedeltapost_id = 123 # Replace with the actual post ID
url = f"https://your-wordpress-site.com/wp-json/wp/v2/posts/{post_id}"
username = "your_username"
app_password = "your_application_password"# Reschedule the post for 1 week from now at 2:00 PM
new_scheduled_time = datetime.now() timedelta(weeks=1)
new_scheduled_time = new_scheduled_time.replace(hour=14, minute=0, second=0, microsecond=0)
new_scheduled_time_str = new_scheduled_time.isoformat()data = {
"status": "future",
"date": new_scheduled_time_str
}response = requests.post(url, auth=(username, app_password), json=data)
if response.status_code == 200:
print("Post rescheduled successfully!")
else:
print("Error rescheduling post:", response.text)
透過遵循本指南,您應該能夠使用 WordPress API 進行身份驗證,並以程式設計方式安排特定發佈時間的貼文。
引用:
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3