在本指南中,我们将探讨如何使用 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